24. Product of Array Except Self
mediumAsked at BrexReturn an output array where each element is the product of all other elements — a prefix/suffix product trick Brex tests in financial aggregation and ledger balance contexts.
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]. You must not use division and run in O(n).
Constraints
2 <= nums.length <= 10^5-30 <= nums[i] <= 30Guaranteed the product of any prefix or suffix fits in a 32-bit integer
Examples
Example 1
nums = [1,2,3,4][24,12,8,6]Example 2
nums = [-1,1,0,-3,3][0,0,9,0,0]Approaches
1. Two extra arrays (prefix + suffix)
Build a prefix product array left-to-right and a suffix array right-to-left, then multiply them pairwise.
- Time
- O(n)
- Space
- O(n)
const n = nums.length, left = new Array(n), right = new 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 left.map((v,i) => v * right[i]);Tradeoff:
2. O(1) extra space using output array
Use the output array itself to store running prefix products, then make a second right-to-left pass with a running suffix product variable, multiplying into the output in place.
- Time
- O(n)
- Space
- O(1)
function productExceptSelf(nums) {
const n = nums.length, out = new Array(n);
out[0] = 1;
for (let i = 1; i < n; i++) out[i] = out[i-1] * nums[i-1];
let suffix = 1;
for (let i = n-1; i >= 0; i--) { out[i] *= suffix; suffix *= nums[i]; }
return out;
}Tradeoff:
Brex-specific tips
Brex asks about fintech infrastructure, multi-currency handling, and spend management algorithms. Expect LeetCode-style DSA focused on hash maps, sorting, and dynamic programming.
Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
Practice these live with InterviewChamp.AI
Drill Product of Array Except Self and other Brex interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →