Product Except Self With Prefix Passes

Build the left-product prefix in one pass, then fold the right-product suffix back over it, so every position skips its own value.

RustData Integrity

Code

rustsnippet
22 lines
fn product_except_self(nums: &[i32]) -> Vec<i32> {
    let n = nums.len();
    // prefix[i] = product of everything left of i
    let mut prefix = vec![1; n];
    for i in 1..n {
        prefix[i] = prefix[i - 1] * nums[i - 1];
    }
    // sweep from the right, folding the suffix product into the result
    let mut suffix = 1;
    let mut out = prefix;
    for i in (0..n).rev() {
        out[i] *= suffix;
        suffix *= nums[i];
    }
    out
}

fn main() {
    println!("{:?}", product_except_self(&[1, 2, 3, 4]));
    println!("{:?}", product_except_self(&[2, 3, 0, 5]));
    println!("{:?}", product_except_self(&[5]));
}

Where the work happens

The code’s whole job belongs to the functions product_except_self and main.

The loop for i in 1..n is the only repeated construct.

What to watch for

  • There is nothing to install: the standard library covers the whole surface.

Using it

The entry-point signature is fn product_except_self(nums: &[i32]) -> Vec<i32>

There are 1 call inside main — product_except_self — executed top to bottom.

Key statements

prefix[i] = prefix[i - 1] * nums[i - 1];

Interactive Tools for This Topic

FAQ

How do you run Product Except Self With Prefix Passes?
Execute it straight away — the program needs nothing beyond the runtime.