ƒ(x) PatternsIntermediate interactive
Sliding Window
A moving range that grows and shrinks in O(n).
sliding_window
step 1 / 13
a
0b
1c
2a
3b
4c
5b
6b
7Window "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