Product of Array Except Self
Difficulty: Medium · Pattern: Prefix Sum · LeetCode #238
Return an array out where out[i] is the product of every element of nums except nums[i]. Don't use division, and run in O(n). (All prefix/suffix products fit in a 32-bit integer.)
Examples
text
nums = [2, 3, 4, 5] → [60, 40, 30, 24]
nums = [-1, 1, 0, -3, 3] → [0, 0, 9, 0, 0]Hints
- out[i] = (product of everything left of i) × (product of everything right of i).
- Fill
outwith left products in one pass, then multiply in right products in a backward pass with a running variable.
Approach
First pass (left → right): out[i] = product of nums[0..i−1], using a running pre. Second pass (right → left): multiply out[i] by a running suf, the product of nums[i+1..]. No division, so zeros are handled naturally. The output array doesn't count as extra space, so it's O(1) extra.
Complexity
Time: O(n). Space: O(1) extra beyond the output.
Python solution
def productExceptSelf(nums):
n = len(nums)
out = [1] * n
pre = 1
for i in range(n):
out[i] = pre
pre *= nums[i]
suf = 1
for i in range(n - 1, -1, -1):
out[i] *= suf
suf *= nums[i]
return outJavaScript solution
function productExceptSelf(nums) {
const n = nums.length, 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.map((v) => (v === 0 ? 0 : v)); // normalize -0 to 0
}