Problem overview
The method productExceptSelf receives an int[] nums and returns an int[] named 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 method 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, 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 the 0 out.
Approach: left product times right product
The obvious brute force multiplies all the other elements for every index. That is two nested loops and O(n²) time, too slow for 100,000 elements. The usual shortcut, dividing the total product by nums[i], is forbidden, and it would also break on zeros.
The key observation is that the product of everything except nums[i] splits into two parts that never include nums[i] itself:
- the product of everything to the left of
i, and - the product of everything to the right of
i.
Both parts can be built with running products. Walking left to right, the product left of i is the product left of i - 1 times nums[i - 1]. Walking right to left works the same way. The lesson stores the left products in answer itself and keeps the right product in a single variable, so no second array is needed.
Take index 2 of [1, 2, 3, 4]. Left of it sit 1 and 2, with product 2. Right of it sits 4, with product 4. The answer is 2 * 4 = 8, which matches answer[2] in the example. Index 0 has an empty left side, whose product is 1, and index 3 has an empty right side, also 1. Those empty products are why both running values start at 1: they leave the other side's product unchanged.
Because the right product is used exactly once per index, and in the order the loop visits the indices, a single variable can stand in for a whole array. That is the step that brings the extra space down from O(n) to O(1).
Step by step
- Store the length.
int n = nums.length;is used by both loops. - Create
answerand setanswer[0] = 1. Java fills a newint[]with zeros, so the first entry must be set by hand. Nothing lies left of index 0, and a product of no numbers is 1. - Left pass. A loop from
i = 1ton - 1setsanswer[i] = answer[i - 1] * nums[i - 1]. After it,answer[i]holds the product of everything left ofi. - Start
suffixat 1. It will hold the product of everything right of the current index. The last element has nothing to its right. - Right pass. A loop from
n - 1down to 0 first doesanswer[i] *= suffix, which multiplies the left product by the right product. Only then does it dosuffix *= nums[i], so that the next index to the left seesnums[i]in its suffix. Swapping those two lines would putnums[i]into its own answer. - Return
answer.
Here is the whole run for [1, 2, 3, 4]. After the left pass, answer is [1, 1, 2, 6]. The right pass then goes:
| i | suffix after the step | answer after the step |
|---|---|---|
| 3 | 4 | [1, 1, 2, 6] |
| 2 | 12 | [1, 1, 8, 6] |
| 1 | 24 | [1, 12, 8, 6] |
| 0 | 24 | [24, 12, 8, 6] |
The solution in Java
class Solution {
public int[] productExceptSelf(int[] nums) {
int n = nums.length;
int[] answer = new int[n];
answer[0] = 1;
for (int i = 1; i < n; i++) {
answer[i] = answer[i - 1] * nums[i - 1];
}
int suffix = 1;
for (int i = n - 1; i >= 0; i--) {
answer[i] *= suffix;
suffix *= nums[i];
}
return answer;
}
}
The Java details worth a closer look:
- Array defaults.
new int[n]is full of zeros. That is harmless for the entries the left pass overwrites, but index 0 must be set to 1 explicitly, or every answer would be 0. - Compound assignment.
answer[i] *= suffixis shorthand foranswer[i] = answer[i] * suffix, and the array element is evaluated once. - Two loops with the same
i. Eachfordeclares its owni, scoped to that loop, so reusing the name is fine. intoverflow. Javaintarithmetic wraps silently. The statement guarantees that every prefix product, suffix product and answer fits in 32 bits, sointis enough here. Without that guarantee it would not be: multiplying 30 by itself seven times in anintgives 395163520 instead of 21870000000.
Complexity
Time: O(n). The method makes two passes over the array, each doing one multiplication or two per element.
Space: O(1) extra. The returned array is not counted, and the method adds only n, i and suffix. Reusing answer for the left products is what avoids a second array.
Edge cases and common mistakes
- One zero.
[5, 0, 4]gives[0, 20, 0]. Only the zero's own position is non-zero, because its product skips the zero. A solution that divides would fail here. - Two or more zeros.
[0, 0, 2]gives[0, 0, 0], since every product includes at least one zero. - Two elements.
[2, 3]gives[3, 2]: each answer is the other element. - Forgetting
answer[0] = 1. The default 0 would spread through every left product. - Updating
suffixbeforeanswer[i]. That multipliesnums[i]into its own answer. - Starting the left loop at 0. It would read
answer[-1]and throwArrayIndexOutOfBoundsException.
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].[5, 0, 4]gives[0, 20, 0].[0, 0, 2]gives[0, 0, 0].
