AlgoPlusAlgoPlus
Learn/Problem-Solving Patterns
Lesson

Sliding Window

A moving slice of neighbouring elements that glides across an array in one pass, updating a running total instead of re-scanning.

8 min read Watch it move Build it

A sliding window is a contiguous slice of an array that glides across it one step at a time. The trick is that when the window moves, almost everything inside it stays the same — so instead of recomputing the slice from scratch, you add the value entering on the right and subtract the value leaving on the left. That turns what looks like nested work into a single left-to-right pass.

The naive version wastes work

Suppose you want the largest sum of any 3 neighbouring numbers in [2, 1, 5, 1, 3, 2]. The brute-force way re-adds three numbers for every position — and if the window were width k over n elements that's O(n·k) work. But consecutive windows overlap almost entirely, so re-summing throws away answers you already had.

The window trick, step by step

  1. 1Sum the first window directly: arr[0..k-1].
  2. 2To slide right one step, add the entering element arr[r] and subtract the leaving element arr[r-k].
  3. 3That single add-and-subtract gives the new window's sum in O(1) — no re-scan.
  4. 4Track the best sum seen as the window sweeps to the end.
Why it's one pass
Each element is added exactly once when it enters the window and subtracted exactly once when it leaves. Every element is touched a constant number of times overall, which is what makes the whole sweep O(n).

Worked trace — max sum of 3 in [2, 1, 5, 1, 3, 2]

  1. 1First window [2, 1, 5] → sum 8. best = 8.
  2. 2Slide: +1 (enters), -2 (leaves) → 8 - 2 + 1 = 7. Window [1, 5, 1].
  3. 3Slide: +3, -17 - 1 + 3 = 9. Window [5, 1, 3]. best = 9.
  4. 4Slide: +2, -59 - 5 + 2 = 6. Window [1, 3, 2].
  5. 5No more elements → answer is 9.
function maxSumK(arr, k) {
  let sum = 0;
  for (let i = 0; i < k; i++) sum += arr[i]; // first window
  let best = sum;
  for (let r = k; r < arr.length; r++) {
    sum += arr[r] - arr[r - k];  // add entering, drop leaving
    best = Math.max(best, sum);
  }
  return best;
}
// maxSumK([2, 1, 5, 1, 3, 2], 3) === 9
Fixed vs. variable windows
The example above is a fixed-width window. A variable window grows its right edge to include more, then shrinks its left edge when a rule breaks — for example finding the longest substring with no repeated character. Same idea, but the width changes by rule instead of staying constant.
OperationTimeSpace
Sliding window · each element enters and leaves onceO(n)O(1)
Naive re-sum · re-adds the whole window every stepO(n·k)O(1)
Check yourself
When the window slides one step right, why don't you re-add every element in it?