10. Product of Array Except Self
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], without using division in $O(n)$ time.
How It Works & Algorithmic Design
Solves using Prefix and Suffix Product Accumulation:
- Left Products Pass: Create result array
res. Setres[0] = 1. For $i$ from $1$ to $n-1$, computeres[i] = res[i - 1] * nums[i - 1](stores product of all elements to the left of $i$). - Right Products Pass: Maintain running
right = 1. Loop backwards from $n-1$ down to $0$:res[i] = res[i] * right.- Update
right = right * nums[i].
- Return:
rescontains total prefix $\times$ suffix products for every index.
Why This Approach Works Best
Avoids division by zero crashes and achieves linear $O(n)$ time using $O(1)$ extra memory (excluding output array).
Example Walkthrough
nums = [1, 2, 3, 4]
Target input.
res = [1, 1, 2, 6]
Products of elements to the left.
res = [24, 12, 8, 6]
Multiplied by suffix running products.
[24, 12, 8, 6]
Products except self.
Answer: Product of array except self
function productExceptSelf(nums) {
const n = nums.length;
const res = new Array(n);
res[0] = 1;
for (let i = 1; i < n; i++) {
res[i] = res[i - 1] * nums[i - 1];
}
let right = 1;
for (let i = n - 1; i >= 0; i--) {
res[i] *= right;
right *= nums[i];
}
return res;
}Combine left prefix products and right suffix products in two simple passes.
Combines prefix product and suffix product without using division.
Reuses output array space to achieve true $O(1)$ auxiliary memory.
Linear time complexity $O(n)$.