Prefix sums
A prefix-sum array stores at i the sum of the first i elements so any range sum becomes two lookups. You pay O(n) to build and O(1) per query.
Detailed Explanation
If you need the sum of xs[l..r] many times, adding those elements each query is O(n) per query. Build pref[0] = 0 and pref[i+1] = pref[i] + xs[i]. Then sum(l..r) = pref[r] - pref[l]. Construction is one pass. Each query is two subtractions.
This works for any group operation with an inverse: sums, XORs, modular sums. It does not work for min or max; those need a sparse table or a segment tree because min(0..r) and min(0..l) do not reconstruct min(l..r).
In Rust you usually store pref as a Vec one longer than xs so pref[xs.len()] is the total and you never underflow the l == 0 case. Overflow is a real issue: i32 prefix sums of a long slice should be i64. The compiler will not promote for you.
2D prefix sums exist for submatrix queries: pref[i+1][j+1] = val + pref[i][j+1] + pref[i+1][j] - pref[i][j]. Inclusion-exclusion recovers a rectangle in O(1). The same overflow and off-by-one care applies.
Prefix sums are a precomputation. If the array mutates, you must rebuild (O(n)) or switch to a Fenwick tree / segment tree (O(log n) update and query). For an immutable slice and many queries, the plain Vec is the right tool.
When you reach for prefix sums: many range-sum queries, or a sliding-window sum you can also write as pref[i] - pref[i-k]. When you reach for a sliding window: a single pass that maintains one active span. When the operation is min, do not use prefix sums.
A prefix array is also the first row of many DP tables. If you already keep dp[i] as "best using the first i items", a range sum of the original input is still pref[r] - pref[l], not dp[r] - dp[l]. Keep the two arrays distinct in names so a later edit does not subtract the wrong thing. Document the exclusive-end convention next to the helper so every caller uses the same l..r.
Code Examples
fn prefix(xs: &[i32]) -> Vec<i64> {
let mut pref = Vec::with_capacity(xs.len() + 1);
pref.push(0);
for x in xs {
pref.push(pref.last().copied().unwrap() + i64::from(*x));
}
pref
}
fn range_sum(pref: &[i64], left: usize, right: usize) -> i64 {
pref[right] - pref[left]
}
fn main() {
let pref = prefix(&[2, 3, 7, 1]);
println!("{}", range_sum(&pref, 1, 3)); // prints: 10 (3 + 7)
}Common Gotchas
Use a wider integer for the prefix
`i32` sums overflow silently in release. Store `i64` (or saturating / wrapping if that is the contract).
Off-by-one on `pref` length
A prefix of length `n+1` with `pref[0] = 0` makes `sum(l..r) = pref[r] - pref[l]` and includes `xs[l]` through `xs[r-1]`.
Min/max are not prefix-summable
There is no inverse. Use another structure.
Mutations invalidate the prefix
Rebuild, or pick a Fenwick tree if updates are frequent.