Start learning free

LESSON 36 OF 314 · PARTIAL SUMS #1

Product of Array Except Self in Rust: Prefix and Suffix Products

Practice O(n) Read the full explanation

You get an array of integers nums.

Return an array answer of the same length.

answer[i] is the product of all the numbers in nums, except the one at index i.

Don't use division.

 

Example 1:

Input: nums = [2,5,1,3]
Output: [15,6,30,10]
Explanation:
answer[0] = 5 * 1 * 3 = 15,
answer[1] = 2 * 1 * 3 = 6,
answer[2] = 2 * 5 * 3 = 30,
answer[3] = 2 * 5 * 1 = 10.

Example 2:

Input: nums = [4,0,-2,5]
Output: [0,-40,0,0]
Explanation: Every product that includes the 0 is 0.
Only answer[1] leaves the 0 out:
answer[1] = 4 * (-2) * 5 = -40.

Example 3:

Input: nums = [0,6,0]
Output: [0,0,0]
Explanation: There are two zeros.
Every product still includes at least one of them.

 

Constraints:

  • nums has 2 to 100,000 numbers.
  • Each number is from -30 to 30.
  • Every answer[i] fits in a 32-bit signed integer.
  • So does the product of all the numbers before any index, or after it.

Note:

Your algorithm should run in O(n) time and use O(1) extra space: the returned array doesn't count.

STEP 1 OF 9
    Ctrl + Enter to check

    RUST · PARTIAL SUMS #1

    Product Of Array Except Self in Rust, explained

    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 i is the entry for i - 1 times nums[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

    1. Store the length in n. It is a usize, which is what ranges and indexes use.
    2. Create answer as a mutable vector of n zeros and set answer[0] to 1. Nothing lies to the left of the first element, and a product of no numbers is 1.
    3. Loop over 1..n to fill the rest of the prefix products.
    4. Set answer[i] to answer[i - 1] * nums[i - 1]. Each entry reuses the one before it.
    5. Declare suffix as a mutable i32 starting at 1. It will hold the product of everything to the right of the current index.
    6. Loop over (0..n).rev(), from the last index down to 0.
    7. Multiply answer[i] by suffix. The entry now holds left product times right product.
    8. Multiply suffix by nums[i], after the line above, so that nums[i] counts for the next index to the left but not for its own entry.
    9. Return answer as 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 value n times. The i32 suffix on the literal gives the vector the same element type as nums, so the products type-check.
    • (0..n).rev() walks a range backwards. Counting down with a usize in a while loop is awkward, because 0usize - 1 wraps (or panics in a debug build); the reversed range stops cleanly at 0.
    • *= multiplies in place, so answer[i] *= suffix reads and writes the same element.
    • Overflow. The lesson builds with optimizations, where i32 overflow wraps silently; in a debug build the same overflow panics. The constraints keep every product in range, so neither happens with valid input. The last suffix *= nums[i], at i = 0, computes the product of the whole vector, which the constraint on prefixes and suffixes also covers.
    • The final expression. answer has 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 suffix too early. If suffix *= nums[i] comes before answer[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] with i = 0 underflows the usize index. The loop starts at 1 because answer[0] is set by hand.
    • Empty input. answer[0] = 1 panics 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].
    Keep going with Rust1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free