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
No sound? Captions are on by default.
3 · Now you drive
Keys:←→ stepSpace playR reset
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.
Step 1 of 25
solution.ts▶ marks the line running now
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;
}
4 · Your turn
0 of 4 problems solved
- Easy01
Best Time to Buy and Sell Stock
Warm-up: the cheapest price so far is your window’s left edge.
- Medium02
Longest Substring Without Repeating Characters
The one you just watched. Write it from memory.
- Medium03
Longest Repeating Character Replacement
Same window, but shrink only when replacements run out.
- Hard04
Minimum Window Substring
Grow until the window is valid, then shrink it as small as it goes.