Skip to content

Start typing to search patterns, problems and pages.

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.

⏱ about 15 minutesNeeds: arrays, setsTime O(n)

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
  1. Easy01

    Best Time to Buy and Sell Stock

    Warm-up: the cheapest price so far is your window’s left edge.

  2. Medium02

    Longest Substring Without Repeating Characters

    The one you just watched. Write it from memory.

  3. Medium03

    Longest Repeating Character Replacement

    Same window, but shrink only when replacements run out.

  4. Hard04

    Minimum Window Substring

    Grow until the window is valid, then shrink it as small as it goes.

UP NEXT · LESSON 4 OF 15StackRemember the past, answer on the way back.