Skip to main content

27. Product of Array Except Self

mediumAsked at Postman

Return an array where each element is the product of all other elements, without using division.

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

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. Total product divided by self

Multiply everything, then divide by each element. Fails on zeros, and the problem forbids division anyway.

Time
O(n)
Space
O(n)
// const total = nums.reduce((a,b)=>a*b, 1); return nums.map(x => total / x);

Tradeoff:

2. Prefix * suffix two-pass

First pass: out[i] = product of everything to the left. Second pass: multiply by a running suffix product walking right-to-left.

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

Tradeoff:

Postman-specific tips

Postman engineers like the two-pass prefix/suffix idiom — it's exactly the shape they use to compute per-stage contribution to total request latency in their monitor dashboards.

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

Practice these live with InterviewChamp.AI →