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)Space O(k)

2 · Watch

Sliding Window in 60 seconds

Say you need the longest stretch of a string with no repeated letters. The obvious way checks every start and every end: 36 windows for 8 letters.

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

    Best Time to Buy and Sell Stock

    LeetCode 121 · Blind 75 · NeetCode 150

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

  2. Medium02

    Longest Substring Without Repeating Characters

    LeetCode 3 · Blind 75 · NeetCode 150

    The one you just watched. Write it from memory.

  3. Medium03

    Longest Repeating Character Replacement

    LeetCode 424 · Blind 75 · NeetCode 150

    Same window, but shrink only when replacements run out.

  4. Hard04

    Minimum Window Substring

    LeetCode 76 · Blind 75 · NeetCode 150

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

UP NEXT · LESSON 4 OF 20Prefix SumKeep running totals, then subtract to get any range.