Skip to main content

11. Product of Array Except Self

mediumAsked at JetBrains

Build an output array where each index is the product of all other elements — JetBrains uses this to test prefix/suffix sweep skills before AST-attribute propagation problems.

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

Problem

Given an integer array nums, return an array answer such that answer[i] is the product of all elements of nums except nums[i]. Solve without division and in O(n) time.

Constraints

  • 2 <= nums.length <= 10^5
  • -30 <= nums[i] <= 30
  • Final answer 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. Brute force

Compute each answer[i] by multiplying everything except nums[i] in an inner loop.

Time
O(n^2)
Space
O(1)
for (let i=0;i<n;i++) { let p=1; for (let j=0;j<n;j++) if (i!==j) p*=nums[j]; ans[i]=p; }

Tradeoff:

2. Prefix and suffix sweep

First pass writes left-products; second pass multiplies in right-products on the fly. Same forward-then-backward AST attribute propagation JetBrains analyzers use.

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

Tradeoff:

JetBrains-specific tips

JetBrains expects you to frame the two passes as forward + backward attribute propagation — the exact technique used by their dataflow analyzers.

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

Practice these live with InterviewChamp.AI →