Sliding Window
A window that slides over a list, growing on the right and shrinking on the left, instead of starting over.
Spot it
Signals in the questionThe answer is a contiguous run: a subarray or a substring.
It asks for the longest, shortest or best run that follows a rule.
The rule can be checked as you go: "at most k", "no repeats", "sum ≥ target".
The idea
O(n) time · O(k) for what's in the window spaceKeep two pointers, l and r. Move r to grow the window. When the rule breaks, move l until it holds again. Each item enters once and leaves once, so it's O(n), not O(n²).
1def longest(s):2 seen, l, best = set(), 0, 03 for r, ch in enumerate(s):4 while ch in seen: # shrink5 seen.remove(s[l]); l += 16 seen.add(ch) # grow7 best = max(best, r - l + 1)8 return best
The template, filled in for Longest Substring Without Repeating Characters. The highlighted lines are the part every problem of this kind shares.
The best, free
One of eachPractice set
Loading your mission…
Common mistakes
1Shrinking with if instead of while: one step left isn't always enough.
2Window length is r − l + 1, not r − l.
3Updating the answer before the window is valid again.
Check yourself
Question 1 of 2"Longest run with at most 2 different letters." Which pattern?