4. Product of Array Except Self

4. Product of Array Except Self

Medium
50.0%
arraydynamic-programming

You’re interviewing for a backend/data engineering role at a FAANG-level company. The interviewer describes a real product scenario:

A large e-commerce or streaming platform runs a multi-stage scoring pipeline to rank content, ads, or products. Each stage produces a multiplier that adjusts the final score.

These multipliers are stored in an integer array nums, where each value may increase or decrease the final score and can include zeros due to missing signals.

For auditing and debugging, the platform wants to know what the final score would look like if any single stage is excluded. For every index i, compute the product of all numbers in the array except nums[i].

This is a common coding interview / DSA question might ask in Google, Amazon, Netflix, Meta, Apple, Microsoft, Uber, and Bloomberg interviews.

Your Task

Given an integer array nums, return an array answer such that:

  • answer[i] is the product of all the elements of nums except nums[i]

You must solve it:

  • Without using division
  • In O(n) time

Input Format

  • nums: an array of integers (can contain positive, negative, and zero values)

Output Format

  • An array of integers answer where answer[i] equals the product of all elements except nums[i]

Examples

Example 1:

Input: nums = [1, 2, 3, 4]
Output: [24, 12, 8, 6]
Explanation: Excluding index 0: 2 × 3 × 4 = 24 Excluding index 1: 1 × 3 × 4 = 12 Excluding index 2: 1 × 2 × 4 = 8 Excluding index 3: 1 × 2 × 3 = 6

Example 2:

Input: nums = [-1, 1, 0, -3, 3]
Output: [0, 0, 9, 0, 0]

Constraints

  • 2 <= nums.length <= 100,000
  • -30 <= nums[i] <= 30
  • The product of any prefix or suffix of nums fits in a 32-bit integer
  • Do not use division
  • Target time complexity is O(n)

Loading editor...

[1, 2, 3, 4]
[24, 12, 8, 6]

Console Output

Click "Run Code" or "Submit" to see results

Your code will be evaluated by AI with instant feedback