Sliding Window: Two Pointers That Only Move Forward
Longest substring without repeating characters, explained by the one reason it is O(n) and not O(n²).
The problem
Given a string, find the length of the longest substring with no repeated characters. "abcabcbb" gives 3 ("abc").
The brute force checks every substring, which is O(n²) or worse. The window version never looks at a character more than twice.
Watch it run
Pick pwwkew or dvdf, which trip up people who just reset the window on a duplicate. Watch how left moves only as far as it must.
Why it is O(n)
It looks like a loop inside a loop, but the inner while is not independent. left only ever moves forward and never past right. Across the whole run:
rightmoves at mostntimes.leftmoves at mostntimes.
That is at most 2n pointer moves in total. This kind of argument is called amortized analysis, and saying that word with the reason behind it is a strong signal in an interview.
The code
def length_of_longest_substring(s: str) -> int:
seen: dict[str, int] = {}
left = best = 0
for right, ch in enumerate(s):
seen[ch] = seen.get(ch, 0) + 1
while seen[ch] > 1: # window is invalid: shrink from the left
seen[s[left]] -= 1
left += 1
best = max(best, right - left + 1)
return bestRecognizing the pattern
Reach for a sliding window when you see:
- A contiguous subarray or substring.
- A property you can maintain incrementally (a count, a sum, a set of distinct items).
- A request for the longest, shortest, or count of windows satisfying a constraint.
| Variant | Window rule |
|---|---|
| Longest unique substring | Shrink while any character count is above 1 |
| Minimum window substring | Grow until valid, then shrink while still valid |
| Max sum of size-k subarray | Fixed size: add the new element, drop the oldest |
| At most K distinct | Shrink while distinct count is above K |