Sliding window
A sliding window maintains a contiguous subarray (or substring) that moves across the input. You add on the right and drop on the left instead of recomputing each span from scratch.
Detailed Explanation
A naive "every subarray" loop is O(n²) or O(n³) depending on the inner work. A window reduces that when the useful spans are contiguous and you can update a summary in O(1) or O(log n) when the window moves.
Fixed length: you want the maximum sum of any k consecutive elements. Compute the sum of the first k, then for each new right index add xs[right] and subtract xs[right - k]. That is O(n). Slices give you xs.windows(k) for the views; you still need the running-sum trick if summing each window from scratch would be O(nk).
Variable length: you want the shortest substring that contains all required characters, or the longest span with at most k distinct items. Grow right until the constraint is satisfied (or broken), then shrink left until it is not. Each index moves at most once, so the pass is O(n) times the cost of the summary update. A HashMap of counts is the usual summary.
Rust pieces: indices left and right, a VecDeque if you need to pop the left value itself, windows / chunks for fixed views, and a map for frequencies. Borrowing the slice while you mutate a window summary is fine — the summary is separate data. Mutating the slice while you hold a windows iterator is not.
When you reach for a sliding window: contiguous spans, running sums, "at most k distinct", substring coverage. When you reach for prefix sums: many queries for "sum of i..j" after preprocessing. When you reach for two pointers on a sorted pair problem: the window is not the right picture; the two ends are candidates, not a span you grow.
Code Examples
fn max_sum_window(xs: &[i32], k: usize) -> Option<i32> {
if k == 0 || k > xs.len() {
return None;
}
let mut sum: i32 = xs[..k].iter().sum();
let mut best = sum;
for i in k..xs.len() {
sum += xs[i] - xs[i - k];
best = best.max(sum);
}
Some(best)
}
fn main() {
println!("{:?}", max_sum_window(&[2, 1, 5, 1, 3, 2], 3)); // prints: Some(9)
}Common Gotchas
`windows(k)` still sums each window in O(k) if you `.sum()` inside
That makes O(nk). Keep a running total for the O(n) version.
Empty or `k == 0` needs a policy
Decide whether to return `None`, `0`, or panic. Do not let `xs[..k]` panic on a short input.
Variable windows need a shrink condition
If `left` never moves, you have a prefix, not a window. Write the invariant in a comment: what the map counts mean.
Do not hold a `windows` iterator while mutating the slice
Collect the result, or use indices.