Skip to main content

11. Product of Array Except Self

mediumAsked at Adyen

Return an array where each entry is the product of all other entries — no division allowed.

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 in O(n) without using the division operator.

Constraints

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

Loop over each index, multiply all others.

Time
O(n^2)
Space
O(1)
const out = [];
for (let i = 0; i < nums.length; i++) {
  let p = 1;
  for (let j = 0; j < nums.length; j++) if (j !== i) p *= nums[j];
  out.push(p);
}
return out;

Tradeoff:

2. Prefix and suffix products

Sweep left to fill prefix products, then right to multiply suffix in place.

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

Tradeoff:

Adyen-specific tips

Adyen ties this to multi-currency cross-rate matrices — they want you to volunteer that division is unsafe because zero-balance accounts mirror the zero-input edge case.

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

Practice these live with InterviewChamp.AI →