21. Product of Array Except Self
mediumAsked at EtsyCompute prefix-product arrays without division — a pattern Etsy uses internally for price-range normalization across listing categories where any element could be zero.
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]. The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer. You must write an algorithm that runs in O(n) time and without using the division operation.
Constraints
2 <= nums.length <= 10^5-30 <= nums[i] <= 30The 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. Brute force
For each index i, multiply all other elements. Two nested loops, O(n^2). Fails on large inputs.
- Time
- O(n^2)
- Space
- O(1) extra
function productExceptSelf(nums) {
const n = nums.length;
const result = new Array(n);
for (let i = 0; i < n; i++) {
let prod = 1;
for (let j = 0; j < n; j++) {
if (j !== i) prod *= nums[j];
}
result[i] = prod;
}
return result;
}Tradeoff:
2. Prefix and suffix products
Build a prefix-product array (product of everything to the left of i) in a left pass. Then do a right pass multiplying each prefix value by the running suffix product. Single allocation, two linear scans.
- Time
- O(n)
- Space
- O(1) extra (output array doesn't count)
function productExceptSelf(nums) {
const n = nums.length;
const result = new Array(n).fill(1);
// Left pass: result[i] = product of nums[0..i-1]
let prefix = 1;
for (let i = 0; i < n; i++) {
result[i] = prefix;
prefix *= nums[i];
}
// Right pass: multiply by product of nums[i+1..n-1]
let suffix = 1;
for (let i = n - 1; i >= 0; i--) {
result[i] *= suffix;
suffix *= nums[i];
}
return result;
}Tradeoff:
Etsy-specific tips
Etsy's data team uses prefix-product patterns for rolling weight normalization in recommendation pipelines. When you describe the two-pass approach, explicitly call out why the output array is not counted in the O(1) space claim — interviewers probe this. Also note the zero-handling edge case: two passes naturally handle multiple zeros without special-casing.
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 Etsy interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →