Sliding Window
Look out of a train window. New scenery slides in on the right, old scenery slides out on the left, and you never re-read the whole view. You only deal with what changed.
2 · Watch
Sliding Window in 60 seconds
3 · Now you drive
Keys:←→ stepSpace playR resetHomeEnd jump
Longest Substring Without Repeating Characters
or try
Lowercase letters a–z, up to 10. Anything else is ignored.window""
seen{}
best so far0
Start with an empty window and an empty set.Step 1 of 25. Window is empty. Best so far 0.
Step 1 of 25
solution.ts
function longest(s: string): number {
const seen = new Set<string>();
let left = 0, best = 0;
for (let r = 0; r < s.length; r++) {
while (seen.has(s[r])) {
seen.delete(s[left]);
left++;
}
seen.add(s[r]);
best = Math.max(best, r - left + 1);
}
return best;
}
▶ marks the line running now
4 · Your turn
0 of 4 problems solved
Start from this
let left = 0, best = 0;
for (let right = 0; right < s.length; right++) {
// Grow: take in the next item.
add(s[right]);
// Shrink from the left until the window is valid.
while (!valid()) remove(s[left++]);
// Only count the window once it's valid.
best = Math.max(best, right - left + 1);
}Easy ways to go wrong
- Updating the answer before the window is valid again.
- Forgetting to remove the left item when you shrink.
- Using it on a problem with negative numbers, where growing can lower the sum.
- Easy01
Best Time to Buy and Sell Stock
Warm-up: the cheapest price so far is your window’s left edge.
Hold the cheapest day so far on the left and let the right edge scan.
- Time
- O(n)
- Space
- O(1)
Also works with Greedy or 1-D DP.
- Medium02
Longest Substring Without Repeating Characters
The one you just watched. Write it from memory.
An unbroken stretch with a rule: grow on the right, shrink on the left when it breaks.
- Time
- O(n)
- Space
- O(k)
- Medium03
Longest Repeating Character Replacement
Same window, but shrink only when replacements run out.
A stretch is fine while its length minus the count of its most common letter is at most k.
- Time
- O(n)
- Space
- O(1)
- Hard04
Minimum Window Substring
Grow until the window is valid, then shrink it as small as it goes.
Grow until it covers everything, then shrink while it still does.
- Time
- O(m + n)
- Space
- O(k)