Skip to main content

238. Product of Array Except Self

mediumAsked at Airbnb

Compute each element's contribution without knowing the whole product — Airbnb's pricing engine uses leave-one-out multiplications when computing the relative impact of a single listing's price on an aggregated market signal.

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

Problem

Given an integer array nums, return an array answer such that answer[i] is equal to the product of all the elements of nums except nums[i]. You must not use division and the solution must run in O(n) time.

Constraints

  • 2 <= nums.length <= 10^5
  • -30 <= nums[i] <= 30
  • The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer

Examples

Example 1

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

Explanation: answer[0]=2*3*4=24, answer[1]=1*3*4=12, answer[2]=1*2*4=8, answer[3]=1*2*3=6.

Example 2

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

Approaches

1. Prefix + suffix arrays

Build a prefix-product array (left to right) and a suffix-product array (right to left). answer[i] = prefix[i] * suffix[i]. Clear and easy to reason about.

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

Tradeoff:

2. O(1) extra space (output array only)

Use the output array itself as the prefix product. Then do a single right-to-left pass multiplying in the suffix product on the fly using a running variable. No extra arrays.

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

Tradeoff:

Airbnb-specific tips

Airbnb values the O(1) space version because it demonstrates you think about memory allocation, not just time. Make sure you mention the no-division constraint before coding — many candidates forget and reach for total-product divided by nums[i], which breaks on zeros. The backward suffix-pass pattern shows up repeatedly in Airbnb's codebase for rolling aggregate computations.

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

Practice these live with InterviewChamp.AI →