Featured article for the topic Sliding window · picked by the needcode team
Sliding window: one pattern, twelve LeetCode problems
Kabir ShahFeatured AuthorPosted · 1 min read
If a problem asks about a contiguous subarray or substring, try a sliding window before anything else.
The template#
def longest_without_repeat(s):
seen, left, best = {}, 0, 0
for right, ch in enumerate(s):
if ch in seen and seen[ch] >= left:
left = seen[ch] + 1
seen[ch] = right
best = max(best, right - left + 1)
return best
Grow the window with right, shrink it with left until it is valid again, and record the answer. Both pointers only move forward, so it's O(n).
Fixed or variable?#
| Window | Shrinks when | Example |
|---|---|---|
| Fixed size k | Always, after k | Max sum of k elements |
| Variable | The window breaks a rule | Longest substring without repeats |
Comments