Problem overview
The method productExceptSelf takes a vector<int> named nums and returns a vector answer of the same length, where answer[i] is the product of every element of nums except nums[i]. Division is not allowed. The statement also asks for O(n) time and O(1) extra space, not counting the returned vector.
For [1, 2, 3, 4] the answer is [24, 12, 8, 6]: the first entry is 2 * 3 * 4, the second 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 the entry at the 0's own position leaves it out.
Approach: left products times right products
The obvious fix is to multiply everything and divide by nums[i]. That is forbidden, and it also breaks on zeros. The brute-force alternative multiplies all the other elements for each index, which costs O(n²).
The faster idea splits each answer into two parts. Everything except nums[i] is the product of the elements to the left of i times the product of the elements to the right of i. Both sides can be built with running products, one pass each:
- Going left to right, keep the product of everything seen so far. Store it in
answer[i]before includingnums[i]. - Going right to left, keep the same kind of running product in a single variable, and multiply it into
answer[i].
The returned vector holds the left products, so no second vector is needed. That is how the extra space stays O(1).
Step by step
- Store the length in an
intnamedn. Both loops use it. - Create
answeras avector<int>of sizenfilled with 0, then setanswer[0]to 1. Nothing lies to the left of the first element, and a product of no numbers is 1. - Loop from 1 to
n - 1. Index 0 is already done. - Set
answer[i]toanswer[i - 1] * nums[i - 1]. The product left ofiis the product left ofi - 1, times the element ati - 1. These are prefix products. - Create
suffixas anintstarting at 1. It will hold the product of everything to the right of the current index. - Loop from
n - 1down to 0. The last element has nothing on its right, which is whysuffixstarts at 1. - Multiply
answer[i]bysuffix. Now it holds left product times right product. - Multiply
suffixbynums[i], after the previous line. Doing it first would putnums[i]into its own answer. - Return
answer.
The solution in C++
class Solution {
public:
vector<int> productExceptSelf(vector<int>& nums) {
int n = nums.size();
vector<int> answer(n, 0);
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 C++ details worth knowing:
vector<int>(n, 0)builds a vector withnelements, all 0. This matters becauseanswer[i]is assigned by index, and indexing a vector doesn't make room:answer[0] = 1on an empty vector would be undefined behaviour.nums.size()is unsigned. The solution copies it into anint, so the loop counterican safely go down to 0 and stop ati >= 0. With an unsigned counter,i >= 0is always true and the loop never ends. Likewisesize() - 1on an empty vector wraps to 18446744073709551615. The constraints guarantee at least two elements, soanswer[0] = 1is safe here.vector<int>& numsis a reference, so the input isn't copied. The solution only reads it.*=updates the element in place, soanswer[i] *= suffixisanswer[i] = answer[i] * suffix.
Tracing the example
For nums = [1, 2, 3, 4], the first loop leaves answer = [1, 1, 2, 6]: the product of everything to the left of each position. The second loop then runs right to left:
| i | answer[i] after *= suffix | suffix after *= nums[i] |
|---|---|---|
| 3 | 6 | 4 |
| 2 | 8 | 12 |
| 1 | 12 | 24 |
| 0 | 24 | 24 |
The result is [24, 12, 8, 6].
Why the two passes cover everything
Take the position i = 2 in [1, 2, 3, 4]. The left pass stored 1 * 2 = 2 there. By the time the right-to-left loop reaches index 2, suffix has absorbed nums[3] and equals 4. The product 2 * 4 = 8 contains every element except nums[2], and no element appears twice. The same argument works at every index, because the left pass never looks past i - 1 and suffix never includes anything at or left of i when it is used.
This is also why the lesson reuses the output vector as the storage for the left products. A common first version keeps three vectors, left, right and answer, which also runs in O(n) time but uses O(n) extra space. Replacing the whole right vector with one number works because each right-side product is needed exactly once, at the moment the loop visits that index.
Complexity
Time is O(n): two loops of n steps each, with one or two multiplications per step. Extra space is O(1): the only additions besides the returned vector are n, suffix and the loop counter.
Edge cases and common mistakes
- Zeros. No division means zeros need no special handling. With
[0, 0, 2]the result is[0, 0, 0], and with[5, 0, 4]it is[0, 20, 0]: only the entry at the single 0 is non-zero. - Two elements.
[2, 3]gives[3, 2]: each entry is the other element. - Wrong update order. Updating
suffixbeforeanswer[i]multipliesnums[i]into its own answer. - Starting the first loop at 0. It would read
answer[-1]andnums[-1], which is out of bounds and undefined behaviour in C++. - Overflow. Signed
intoverflow is undefined behaviour. The statement guarantees that every prefix product, suffix product and answer fits in 32 bits, so this solution is safe on valid input.
