Problem overview
The method productExceptSelf receives an array of numbers, nums, and returns an array answer of the same length. Each answer[i] is the product of every element of nums except nums[i]. Division is not allowed, and the algorithm must run in O(n) time with O(1) extra space, not counting the returned array.
For nums = [1, 2, 3, 4] the answer is [24, 12, 8, 6]: answer[0] is 2 * 3 * 4 = 24, answer[1] is 1 * 3 * 4 = 12, and so on. For [-1, 1, 0, -3, 3] the answer is [0, 0, 9, 0, 0], because every product that includes the zero is zero and only answer[2] leaves it out.
Approach: left products times right products
The obvious plan multiplies all the elements and divides by nums[i] for each position. It fails twice: division is banned, and a zero in the array makes the total 0, so dividing gives NaN (for [1, 2, 0, 4] the division idea yields [0, 0, NaN, 0] in TypeScript). Multiplying out the other elements for every position works, but costs O(n²).
The key observation is that "everything except nums[i]" splits into two parts: everything to the left of i and everything to the right. So answer[i] is the product of the left part times the product of the right part. Both parts can be built with running products:
- The product to the left of
iis the product to the left ofi - 1, timesnums[i - 1]. These are prefix products. - The product to the right of
iis the product to the right ofi + 1, timesnums[i + 1]. Walking from the right end, one running variable is enough.
The first pass stores the prefix products directly in answer, which is why no second array is needed. The second pass walks backwards, multiplying each entry by the running right-hand product.
On [1, 2, 3, 4] the first pass leaves answer as [1, 1, 2, 6]: the product of nothing is 1, then 1, then 1 * 2, then 1 * 2 * 3. The second pass then goes from the right, and after each index answer and suffix look like this:
| i | answer after the step | suffix after the step |
|---|---|---|
| 3 | [1, 1, 2, 6] | 4 |
| 2 | [1, 1, 8, 6] | 12 |
| 1 | [1, 12, 8, 6] | 24 |
| 0 | [24, 12, 8, 6] | 24 |
Step by step
- Store the length in a
constnamedn. Both loops use it. - Create
answerwithnzeros and setanswer[0]to 1. Nothing lies to the left of the first element, and the product of no numbers is 1. - Loop from index 1 up to
n - 1, since index 0 is already set. - Extend the prefix product:
answer[i]isanswer[i - 1] * nums[i - 1]. After this loopanswer[i]holds the product of everything left ofi. - Create
suffixwithlet, starting at 1. It will hold the product of everything right of the current index. The last element has nothing on its right, hence 1. - Loop from
n - 1down to 0. - Multiply
answer[i]bysuffix. The left part is already inanswer[i], so now it holds left times right. - Multiply
suffixbynums[i], after the previous line. If it came first,answer[i]would includenums[i]itself. Now the suffix is correct for the next index to the left. - Return
answer.
The solution in TypeScript
class Solution {
productExceptSelf(nums: number[]): number[] {
const n = nums.length;
const answer: number[] = new Array(n).fill(0);
answer[0] = 1;
for (let i = 1; i < n; i++) {
answer[i] = answer[i - 1] * nums[i - 1];
}
let suffix = 1;
for (let i = n - 1; i >= 0; i--) {
answer[i] *= suffix;
suffix *= nums[i];
}
return answer;
}
}
Some TypeScript details:
new Array(n).fill(0)builds an array ofnzeros. Withoutfill,new Array(n)has empty slots, and the annotationnumber[]would not change that at run time. Types are erased when the code is compiled to JavaScript.constfor the array,letforsuffix.const answeronly means the variable always points at the same array. Its elements can still change.suffixgets a new value on every step, so it needslet.numberis a double. The constraints promise that every prefix, suffix and answer fits in 32 bits, so the products are exact. Beyond 2^53 a product would silently lose precision instead of overflowing.*=multiplies a variable by a value and stores the result back, soanswer[i] *= suffixis the same asanswer[i] = answer[i] * suffix.
Complexity
Time: O(n). There are two loops over the array, each doing a constant amount of work per element.
Space: O(1) extra. The returned array is the output, and the only other storage is n and suffix. Keeping the prefix products in answer itself is what makes this possible.
Edge cases and common mistakes
- Zeros. One zero makes every answer 0 except the one at the zero's own index. Two zeros make every answer 0. The two-pass method needs no special case:
[0, 0, 2]gives[0, 0, 0], and[2, 0, 3, 4]gives[0, 24, 0, 0]. - Negative zero. JavaScript numbers have a signed zero. For
[-1, 0, 5]the result prints as[0, -5, -0], because the prefix product -1 * 0 is-0. It still compares equal to 0 with===, butObject.is(answer[2], 0)isfalse. - Updating in the wrong order. Multiplying
suffixbynums[i]before using it putsnums[i]intoanswer[i]. - Starting the first loop at 0. It would read
answer[-1], which isundefined, and the product becomesNaN. - Two elements. For
[2, 3]the answer is[3, 2]: each answer is the other element.
Testing
nums = [1, 2, 3, 4]gives[24, 12, 8, 6].nums = [-1, 1, 0, -3, 3]gives[0, 0, 9, 0, 0].nums = [2, 3]gives[3, 2].nums = [5, 0, 2]gives[0, 10, 0].
