Problem overview
The method productExceptSelf(nums) takes an array of integers 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 statement asks for O(n) time with O(1) extra space, where the returned array doesn't count.
For nums = [1, 2, 3, 4] the answer is [24, 12, 8, 6]: answer[0] is 2 * 3 * 4, answer[1] is 1 * 3 * 4, and so on. For [-1, 1, 0, -3, 3] the answer is [0, 0, 9, 0, 0]. Every product that includes the 0 is 0, and only answer[2] leaves it out.
Approach: products from the left, then from the right
The obvious idea multiplies all the elements and divides by nums[i]. That is forbidden, and it also breaks as soon as the array contains a 0. Another idea computes each answer with an inner loop over the other elements, which costs O(n²).
The faster idea splits every answer into two halves: the product of everything to the left of i times the product of everything to the right of i. Both halves can be built with running products, so the whole thing takes two passes.
- Left to right: store in
answer[i]the product of the elements before indexi. Each entry reuses the previous one:answer[i] = answer[i - 1] * nums[i - 1]. These are prefix products. - Right to left: keep one variable,
suffix, holding the product of the elements after the current index. Multiply it intoanswer[i], then foldnums[i]into it for the next step.
The right side needs only a single variable because each suffix product is used exactly once, at the moment the loop passes over its index. That is why the extra space stays O(1), since the only array is the one we return.
On [1, 2, 3, 4] the first pass leaves [1, 1, 2, 6] in answer. The second pass runs from index 3 down to 0:
| 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 |
The zero example shows why the split works even when the array contains 0. On [-1, 1, 0, -3, 3] the first pass leaves [1, -1, -1, 0, 0]. The suffix value used at each index, from left to right, is [0, 0, -9, 3, 1]. Multiplying them index by index gives [0, 0, 9, 0, 0]. At index 2 both halves are non-zero (-1 on the left, -9 on the right), and everywhere else one half already contains the zero.
Step by step
- Store the length in a
constnamedn, because both loops need it. - Create
answerasnew Array(n).fill(0). A barenew Array(n)has empty slots, sofillgives it real values to overwrite. Then setanswer[0] = 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. Index 0 is already done. - Extend the left product. The product left of
iis the product left ofi - 1timesnums[i - 1]. - Declare
suffixwithlet, starting at 1, because it changes on every step and the last element has nothing to its right. - Loop from
n - 1down to 0. - Combine the halves with
answer[i] *= suffix. The left product is already stored, andsuffixis the right product. - Update
suffixafter that withsuffix *= nums[i]. The order matters: doing it first would putnums[i]into its own answer. - Return
answer.
The solution in JavaScript
class Solution {
productExceptSelf(nums) {
const n = nums.length;
const answer = 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 JavaScript details worth knowing:
constdoes not freeze the array.answeris declared withconst, which only stops you from reassigning the variable. Its elements can still change, which is what both loops do.suffixholds a number that must change, so it useslet.*=is shorthand.answer[i] *= suffixmeansanswer[i] = answer[i] * suffix.- Negative zero. JavaScript numbers are doubles, and a double has both
0and-0. Multiplying 0 by a negative number gives-0. For[-1, 1, 0, -3, 3]the function returns an array thatconsole.logprints as[ -0, 0, 9, -0, 0 ]. Comparisons treat the two zeros as equal:r[0] === 0istrue, andString(r[0])gives"0". OnlyObject.is(r[0], 0)tells them apart, and it returnsfalsehere. You don't need to fix anything for this problem.
Complexity
Time: O(n). The function makes two passes over the array, and each iteration does a constant amount of work.
Space: O(1) extra. Besides the returned array, the function keeps only n, suffix and the loop counters.
Edge cases and common mistakes
- Using division. Dividing the total product by
nums[i]fails for zeros, since dividing by 0 givesInfinityorNaNin JavaScript. It's also against the rules. - One zero or several. With
[0, 4, 5]the function returns[20, 0, 0]: only the zero's own position gets a non-zero value. With[0, 0]every answer is 0. - Updating
suffixtoo early. Ifsuffix *= nums[i]runs beforeanswer[i] *= suffix, each answer wrongly includesnums[i]. - Starting
suffixoranswer[0]at 0. Both must start at 1, the identity for multiplication. Starting at 0 turns everything into 0. - Forgetting
fill.new Array(n)alone creates empty slots, so the loop could not rely on them. - Off-by-one loop bounds. The first loop starts at 1 because it reads
answer[i - 1]. The second must include index 0, so it usesi >= 0.
Testing
[1, 2, 3, 4]gives[24, 12, 8, 6].[-1, 1, 0, -3, 3]gives[0, 0, 9, 0, 0].[2, 3]gives[3, 2].[0, 4, 5]gives[20, 0, 0].[5, -2]gives[-2, 5].
