learn/Algorithms/Sliding Window
ƒ(x) PatternsIntermediate interactive

Sliding Window

A moving range that grows and shrinks in O(n).

sliding_window
step 1 / 13
a
0
b
1
c
2
a
3
b
4
c
5
b
6
b
7

Window "a" — longest so far: "a" (1).

windowbest window
speed1×

How it works

The sliding-window pattern maintains a contiguous range that expands and contracts as it scans, reusing work instead of recomputing each subarray. It turns brute-force O(n·k) substring and subarray problems into a single O(n) sweep.

Mental models

  • Expand the right edge to include; shrink the left to stay valid.
  • Each element enters and leaves the window at most once → O(n).

Complexity

Time
O(n)
Space
O(k)window contents

Reach for it when

  • Longest substring problems
  • Max sum subarray of size k
  • Rate limiting