The sliding window pattern: how to spot it
Updated
A sliding window keeps a contiguous range and its state (a sum, counts, distinct values) and updates them as the range moves, instead of recomputing every subarray. Fixed windows slide by one; variable windows grow on the right and shrink on the left.
When to reach for it
- The question is about a contiguous subarray or substring.
- It asks for the longest, shortest, or best range that meets a condition.
- The condition can be checked from state you can add to and remove from (a sum, character counts).
- A brute force restarts from every starting index.
The usual shape
left = 0
state = empty
best = initial
for right, x in enumerate(items):
add(state, x)
while invalid(state):
remove(state, items[left])
left += 1
best = better(best, right - left + 1)
return best4 LeetCode sliding window problems, easiest first
- Maximum Average Subarray I easy
Seed k cells, then slide. Max average is max sum over a fixed length.
- Longest Substring Without Repeating Characters medium
A repeat makes the window invalid. Shrink left until the character is unique again.
- Minimum Size Subarray Sum medium
Expand until the sum is enough, then shrink for the shortest cover.
- Max Consecutive Ones III medium
Zeros are the budget. Too many zeros: slide left until you are back under k.
Skills these problems use
Each one has a free lesson with worked examples and a drill.
- Fix the window length in advance
- Slide by dropping left and adding right
- Maintain the sum of the window
- Unique-character window shrinks on a repeat
- Maintain distinct count in the window
- Track the best valid length
- Shrink to the smallest valid window
- Track the best valid bounds
- At most k zeros in the window
- Shrink while the window is invalid
- Longest valid window expands greedily
check which skills you have 10 minutes, free, no account.