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.
Code
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
Big-O Complexity VisualizerVisualize and compare algorithm time complexities like O(1), O(log n), O(n), O(n log n), and O(n²). Plot growth curves to understand performance scaling at a glance.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- How do you run Product Except Self With Prefix Passes?
- Execute it straight away — the program needs nothing beyond the runtime.
Report a problem with this exampleOpens a pre-filled issue on GitHub.