Problem overview
The function product_except_self receives a vector of integers, nums, and returns a vector 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 function must run in O(n) time with O(1) extra space, not counting the returned vector.
For nums = [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] it is [0, 0, 9, 0, 0], because every product that includes the zero is zero and only the middle entry leaves it out. The constraints promise that every prefix product, suffix product and answer fits in an i32.
Approach: left product times right product
The obvious solution multiplies everything and divides by nums[i]. Division is ruled out, and it would also break on zeros. The next idea, a nested loop that multiplies all the other elements for each i, takes O(n²) time.
The faster idea splits each answer in two. The product of everything except nums[i] is the product of everything to the left of i times the product of everything to the right. Both sides are running products, so each can be computed in a single pass:
- A left-to-right pass builds the prefix products: the entry for
iis the entry fori - 1timesnums[i - 1]. - A right-to-left pass keeps the suffix product in one variable and multiplies it into each entry.
The prefix products live in the output vector itself, so the only extra memory is one integer. That is how the lesson reaches O(1) extra space.
Step by step
- Store the length in
n. It is ausize, which is what ranges and indexes use. - Create
answeras a mutable vector ofnzeros and setanswer[0]to 1. Nothing lies to the left of the first element, and a product of no numbers is 1. - Loop over
1..nto fill the rest of the prefix products. - Set
answer[i]toanswer[i - 1] * nums[i - 1]. Each entry reuses the one before it. - Declare
suffixas a mutablei32starting at 1. It will hold the product of everything to the right of the current index. - Loop over
(0..n).rev(), from the last index down to 0. - Multiply
answer[i]bysuffix. The entry now holds left product times right product. - Multiply
suffixbynums[i], after the line above, so thatnums[i]counts for the next index to the left but not for its own entry. - Return
answeras the last expression.
Here is a run on [1, 2, 3, 4]. After the first pass, answer is [1, 1, 2, 6]: each entry is the product of the elements before it. The second pass then gives:
i = 3: answer = [1, 1, 2, 6], suffix = 4
i = 2: answer = [1, 1, 8, 6], suffix = 12
i = 1: answer = [1, 12, 8, 6], suffix = 24
i = 0: answer = [24, 12, 8, 6], suffix = 24
The printed suffix is the value after its update, so it already includes nums[i]. At i = 3 the entry is multiplied by 1, because nothing lies to its right. At i = 2 it is multiplied by 4, giving 2 * 4 = 8.
The solution in Rust
impl Solution {
fn product_except_self(nums: Vec<i32>) -> Vec<i32> {
let n = nums.len();
let mut answer = vec![0i32; n];
answer[0] = 1;
for i in 1..n {
answer[i] = answer[i - 1] * nums[i - 1];
}
let mut suffix = 1i32;
for i in (0..n).rev() {
answer[i] *= suffix;
suffix *= nums[i];
}
answer
}
}
The Rust details worth a closer look:
vec![0i32; n]repeats a valuentimes. Thei32suffix on the literal gives the vector the same element type asnums, so the products type-check.(0..n).rev()walks a range backwards. Counting down with ausizein awhileloop is awkward, because0usize - 1wraps (or panics in a debug build); the reversed range stops cleanly at 0.*=multiplies in place, soanswer[i] *= suffixreads and writes the same element.- Overflow. The lesson builds with optimizations, where
i32overflow wraps silently; in a debug build the same overflow panics. The constraints keep every product in range, so neither happens with valid input. The lastsuffix *= nums[i], ati = 0, computes the product of the whole vector, which the constraint on prefixes and suffixes also covers. - The final expression.
answerhas no semicolon, so it is the value the function returns, moved out to the caller.
Complexity
Time: O(n). Two passes over the vector, each doing a constant amount of work per element.
Space: O(1) extra. The result vector is required by the problem and doesn't count. The only additional storage is n and suffix.
Edge cases and common mistakes
- Zeros. One zero turns every answer to zero except the one at the zero's own position.
[2, 0, 3]gives[0, 6, 0]. Two zeros zero everything:[0, 0, 5]gives[0, 0, 0]. The prefix and suffix approach handles this without any special case, which a division-based solution can't do. - Two elements. Each answer is the other element:
[2, 3]gives[3, 2]and[7, -2]gives[-2, 7]. - Negative numbers. The signs multiply as usual.
[-1, 1, 0, -3, 3]gives[0, 0, 9, 0, 0], where the 9 is (-1) * 1 * (-3) * 3. - Updating
suffixtoo early. Ifsuffix *= nums[i]comes beforeanswer[i] *= suffix, each entry includes its own element, and every answer becomes the product of the whole vector. - Starting the first loop at 0.
answer[i - 1]withi = 0underflows theusizeindex. The loop starts at 1 becauseanswer[0]is set by hand. - Empty input.
answer[0] = 1panics on an empty vector. The constraints guarantee at least two elements.
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 = [2, 0, 3]gives[0, 6, 0].nums = [0, 0, 5]gives[0, 0, 0].
