Skip to main content

15. Product of Array Except Self

mediumAsked at Flipkart

Compute each index's product-of-all-others without division — Flipkart uses it to test the prefix-suffix trick that powers their cross-sell ranking scores.

By Alex Chen, Founder, InterviewChamp.AI · Last verified

Problem

Given an integer array nums, return an array answer such that answer[i] equals the product of all elements except nums[i]. Solve it in O(n) time without using division and the output array does not count as extra space.

Constraints

  • 2 <= nums.length <= 10^5
  • -30 <= nums[i] <= 30
  • Product fits in a 32-bit integer

Examples

Example 1

Input
nums = [1,2,3,4]
Output
[24,12,8,6]

Example 2

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

Approaches

1. Brute force

For each index multiply every other element.

Time
O(n^2)
Space
O(n)
// nested loop; multiply all j != i

Tradeoff:

2. Prefix and suffix sweep

First pass writes the prefix product into answer[i]; second pass multiplies the running suffix product from the right. O(n) time, O(1) auxiliary memory.

Time
O(n)
Space
O(1) aux
function productExceptSelf(nums) {
  const n = nums.length, out = new Array(n);
  out[0] = 1;
  for (let i = 1; i < n; i++) out[i] = out[i-1] * nums[i-1];
  let suffix = 1;
  for (let i = n - 1; i >= 0; i--) {
    out[i] *= suffix;
    suffix *= nums[i];
  }
  return out;
}

Tradeoff:

Flipkart-specific tips

Flipkart screeners reward you for proactively asking about zero handling and integer overflow — both come up in their marketplace-ranking score normalization.

Solve it now

Free. No sign-up. Python and JavaScript run instantly in your browser.

Output

Press Run or Cmd+Enter to execute

Practice these live with InterviewChamp.AI

Drill Product of Array Except Self and other Flipkart interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →