Skip to main content

13. Product of Array Except Self

mediumAsked at Confluent

Return the array of products of all elements except self without using division — Confluent uses it to test prefix/suffix passes, the same pattern used for partition-aware running aggregates.

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 of nums except nums[i]. Solve it in O(n) without division.

Constraints

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

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. Two arrays prefix/suffix

Build prefix and suffix product arrays, then multiply them.

Time
O(n)
Space
O(n)
const left=Array(n),right=Array(n);
left[0]=1; for(let i=1;i<n;i++) left[i]=left[i-1]*nums[i-1];
right[n-1]=1; for(let i=n-2;i>=0;i--) right[i]=right[i+1]*nums[i+1];
return nums.map((_,i)=>left[i]*right[i]);

Tradeoff:

2. O(1) extra space two-pass

First pass writes prefix products into the output. Second pass walks right-to-left multiplying by a running suffix accumulator, giving constant extra space beyond the output.

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

Tradeoff:

Confluent-specific tips

Confluent likes when you tie prefix/suffix passes to streaming windowed aggregates — explain how a stateful processor can checkpoint the running product per partition so exactly-once semantics survive consumer-group rebalance.

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 Confluent interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →