Intuition
Say you want the sum of every 3 neighbouring values in [4, 2, 9, 7, 5]. Adding each run of 3 from scratch repeats work: 2 + 9 gets added twice. Instead, keep a running total. When the window slides one step right, add the value coming in and subtract the one going out. Each step costs two operations, however wide the window is.
That’s the whole technique. The window is a range left..right, and you never rebuild it, only slide its edges.
Fixed and variable windows
- Fixed size: the window is always k wide. Slide both edges together: add
a[right], subtracta[right − k]. Used for moving averages, and for “maximum sum of k neighbours”. - Variable size: the window grows and shrinks to meet a condition. The figure shows this kind. It’s used for “shortest run with a sum of at least S” and “longest substring with no repeated letter”.
How the variable window works
To find the shortest run of neighbours that adds up to at least a target:
- Move
rightforward one step and add its value to the sum. The window grows. - While the sum reaches the target, record the window’s length if it’s the shortest so far, then shrink it: subtract
a[left]and moveleftforward. - Repeat until
rightreaches the end.
def shortest_window(a, target):
"""Length of the shortest run of neighbours summing to at least target.
Values must be positive. Returns 0 if no run is long enough."""
best = 0
total = left = 0
for right in range(len(a)):
total += a[right]
while total >= target:
if best == 0 or right - left + 1 < best:
best = right - left + 1
total -= a[left]
left += 1
return best// Length of the shortest run of neighbours summing to at least target.
// Values must be positive. Returns 0 if no run is long enough.
function shortestWindow(a, target) {
let best = 0;
let total = 0;
let left = 0;
for (let right = 0; right < a.length; right++) {
total += a[right];
while (total >= target) {
if (best === 0 || right - left + 1 < best) {
best = right - left + 1;
}
total -= a[left];
left++;
}
}
return best;
}// shortestWindow returns the length of the shortest run of neighbours
// summing to at least target. Values must be positive. It returns 0 if
// no run is long enough.
func shortestWindow(a []int, target int) int {
best, total, left := 0, 0, 0
for right := 0; right < len(a); right++ {
total += a[right]
for total >= target {
if best == 0 || right-left+1 < best {
best = right - left + 1
}
total -= a[left]
left++
}
}
return best
}// Length of the shortest run of neighbours summing to at least target.
// Values must be positive. Returns 0 if no run is long enough.
fn shortest_window(a: &[u32], target: u32) -> usize {
let (mut best, mut total, mut left) = (0, 0, 0);
for right in 0..a.len() {
total += a[right];
while total >= target {
if best == 0 || right - left + 1 < best {
best = right - left + 1;
}
total -= a[left];
left += 1;
}
}
best
}Why it’s O(n)
There are two loops, but right moves forward n times in total, and left can only follow behind it, so it also moves at most n times in total. Neither pointer ever moves back. That’s at most 2n pointer moves, which is O(n). The “pointer moves” counter in the figure never goes above twice the size.
Checking every start and end instead is O(n²), and recomputing each sum on top of that is O(n³).
Where it shows up
| Problem | Window |
|---|---|
| Maximum sum of k neighbours | Fixed, size k |
| Moving average of the last k readings | Fixed, size k |
| Shortest subarray with sum ≥ S | Variable, shrink while the sum is ≥ S |
| Longest substring without repeating characters | Variable, shrink while there’s a repeat (keep a set or hash map) |
| Smallest window containing all given letters | Variable, with letter counts |
Common mistakes
- Recomputing the sum each step. That throws away the whole point. Keep a running total.
- Shrinking with
ifinstead ofwhile. One new value can let several old ones go. - Using it with negative values. Shrinking assumes the sum drops when a value leaves. With negatives, it can rise.
Check yourself
Check yourself
In [2, 3, 1, 2, 4, 3], what's the shortest run with a sum of at least 7?
[4, 3] adds up to 7 with two values. No single value reaches 7.
Check yourself
Why is the variable window O(n) even though there's a loop inside a loop?
The inner loop moves left, which never goes back. Over the whole run it moves at most n times, so both loops together do at most 2n moves.
Sources
- Steven Halim and Felix Halim, Competitive Programming 3 (2013), “Sliding Window.”
- LeetCode problem 209, “Minimum Size Subarray Sum.”
Finished this page?
Your list