Sliding window: how it works and when to use it

A sliding window keeps a run of neighbors and moves it along the input, so each item is handled once. Signals, a worked example, code and practice.

Updated About 7 minutes to read

On this page

The video

Longest Substring Without Repeating Characters

LeetCode 3Open the video page

Chapters

  1. Play from 0:00The longest run without repeats
  2. Play from 0:08An example: pwwkew
  3. Play from 0:21Checking every run is slow
  4. Play from 0:30A sliding window
  5. Play from 0:48A map of last positions
  6. Play from 0:56Walking through pwwkew
  7. Play from 1:11The best length so far
  8. Play from 1:22The code in JavaScript
  9. Play from 1:40Why left never moves back
  10. Play from 1:54Each letter is visited once
  11. Play from 2:09Recap: one pass is enough

Transcript

Show the whole transcriptHide the transcript
  1. Play from 0:00

    This is LeetCode problem three.

  2. Play from 0:02

    Given a string, find the length of the longest substring with no repeated characters.

  3. Play from 0:09

    Take the string pwwkew.

  4. Play from 0:13

    A substring is a run of letters that sit next to each other.

  5. Play from 0:16

    The run wke has no repeats, so the answer is three.

  6. Play from 0:22

    One way is to check every substring for repeats.

  7. Play from 0:25

    That work grows like n squared or worse, which is slow for long strings.

  8. Play from 0:30

    A faster idea is a sliding window.

  9. Play from 0:34

    We keep a left edge and a right edge.

  10. Play from 0:37

    The right edge moves forward one letter at a time.

  11. Play from 0:42

    When a letter repeats, the left edge jumps past its earlier copy.

  12. Play from 0:48

    To jump quickly, we keep a map.

  13. Play from 0:50

    It stores the last position where we saw each letter.

  14. Play from 0:54

    Positions count from zero.

  15. Play from 0:57

    At position zero, p is new.

  16. Play from 1:00

    At one, w is new, so the length is two.

  17. Play from 1:04

    At two, w repeats.

  18. Play from 1:07

    It was last seen at one, so left moves to two.

  19. Play from 1:11

    Then k and e are new, so the best length becomes three.

  20. Play from 1:15

    At five, w repeats.

  21. Play from 1:18

    It was last seen at two, so left moves to three.

  22. Play from 1:23

    Here is the JavaScript.

  23. Play from 1:25

    We create the map, with left and best at zero.

  24. Play from 1:29

    Right moves across the string.

  25. Play from 1:31

    If the letter was seen inside the window, left jumps past it.

  26. Play from 1:35

    We save its position and update best.

  27. Play from 1:38

    Then we return best.

  28. Play from 1:40

    The map can hold old positions left of the window.

  29. Play from 1:44

    In abba, the last a was seen at zero, but left is at two.

  30. Play from 1:49

    The check against left ignores it, so left never moves backward.

  31. Play from 1:55

    Each letter is visited once, so the time grows in step with the string length.

  32. Play from 2:00

    The map holds one entry per distinct letter, so extra memory depends on the alphabet.

  33. Play from 2:05

    Map lookups take constant time on average.

  34. Play from 2:09

    A sliding window with a map of last positions finds the longest substring without repeats in one pass.

A sliding window is a run of neighbors in a list or a string. You move it from left to right. Each step, one new item comes in on the right. When the run breaks a rule, items leave on the left. You keep a small summary of what is inside, like a sum or a count of letters, and update it as items come and go. You never recount the whole run. That turns "check every run" into a single pass.

The idea in one minute

Many problems ask about runs of neighbors. "The longest stretch with no repeated letter." "The biggest total of 3 numbers in a row." "The shortest stretch that adds up to at least 7."

The slow way checks every possible run. A list of 8 items has 36 runs: 8 runs of one item, 7 runs of two, and so on, down to 1 run of all eight. The count grows with the square of the length. A list of 10,000 items has about 50 million runs.

The window avoids that. Two markers, left and right, show where the run starts and ends.

  • right moves one step every time, so every item comes in once.
  • left only moves forward, so every item leaves at most once.

So each item is handled at most twice, however long the input is.

There are two kinds of window:

  • Fixed size. The window is always k items wide. Each step, one item comes in and one goes out.
  • Grow and shrink. The window grows on the right. When it breaks the rule, it shrinks from the left until the rule holds again.

When to use it

Look for these signals in the problem:

  • The input is a list or a string, and the answer is about a run of neighbors. The words "substring", "subarray", "in a row" or "consecutive" are strong hints.
  • You want the longest, shortest, biggest or smallest run that follows a rule.
  • When you add an item on the right, you can update your summary in one step. When you drop an item on the left, you can undo it in one step.
  • For "grow and shrink" windows, the rule is steady. Making a run longer either always helps or always hurts, never both. "No repeats" only gets harder as the run grows. "A total of at least 7" with positive numbers only gets easier.

A sliding window is a poor fit when the items don't need to be neighbors. That kind of problem is about a "subsequence". It also fails when adding an item can both fix and break the rule. Sums with negative numbers are the usual trap, as the mistakes section below explains.

A worked example

This is the example from the video. It is LeetCode 3, Longest Substring Without Repeating Characters. In our words: find the length of the longest run of neighboring characters where no character appears twice.

Our string is abcbdeaf, with positions 0 to 7.

We keep a map from each character to the last position where we saw it. A map is a lookup table: you give it a key, like "b", and it gives back the value stored for that key in one step.

Each step, right reads one character. If we saw it before inside the window, left jumps to just past that earlier copy. Then we write down the new position and check the window's length.

right letter left window best
0 a 0 a 1
1 b 0 ab 2
2 c 0 abc 3
3 b 2 cb 3
4 d 2 cbd 3
5 e 2 cbde 4
6 a 2 cbdea 5
7 f 2 cbdeaf 6

Two steps matter:

  • Step 3. right finds a second b. The map says the first b was at position 1, which is inside the window. So left jumps to 2, right after it. The window becomes cb.
  • Step 6. right finds a second a. The map says the first a was at position 0. But the window now starts at 2, so that old a is no longer inside it. We ignore it, and left stays put.

The answer is 6, the run cbdeaf from position 2 to 7.

The code in JavaScript

function lengthOfLongestSubstring(s) {
  const last = new Map(); // character -> the last index where we saw it
  let left = 0;
  let best = 0;
  for (let right = 0; right < s.length; right++) {
    const ch = s[right];
    if (last.has(ch) && last.get(ch) >= left) {
      left = last.get(ch) + 1; // jump just past the earlier copy
    }
    last.set(ch, right);
    best = Math.max(best, right - left + 1);
  }
  return best;
}

lengthOfLongestSubstring("abcbdeaf"); // 6

The check last.get(ch) >= left is what makes step 6 work. Without it, left could jump backward.

A fixed-size window

For "the biggest total of k numbers in a row", add the new number and subtract the one that just left.

function maxSumOfK(nums, k) {
  let sum = 0;
  for (let i = 0; i < k; i++) sum += nums[i]; // the first window
  let best = sum;
  for (let right = k; right < nums.length; right++) {
    sum += nums[right] - nums[right - k]; // one in, one out
    best = Math.max(best, sum);
  }
  return best;
}

maxSumOfK([2, 1, 5, 1, 3, 2], 3); // 9, from 5 + 1 + 3

A grow-and-shrink window

For "the shortest run with a total of at least target", grow on the right. While the window still works, record it and shrink from the left. This version expects positive numbers.

function shortestWithSumAtLeast(nums, target) {
  let left = 0;
  let sum = 0;
  let best = Infinity;
  for (let right = 0; right < nums.length; right++) {
    sum += nums[right]; // grow
    while (sum >= target) { // shrink while the window still works
      best = Math.min(best, right - left + 1);
      sum -= nums[left];
      left++;
    }
  }
  return best === Infinity ? 0 : best;
}

shortestWithSumAtLeast([2, 3, 1, 2, 4, 3], 7); // 2, from 4 + 3

Most window problems are one of these two shapes. Only the rule and the summary change.

How fast is it?

Programmers describe speed with Big-O notation. It says how the work grows as the input grows, and ignores fixed costs. O(n) means the work grows in step with n, the length of the input. O(n²) means it grows with the square: double the input, and the work goes up four times.

  • Time: O(n). right moves n times. left also moves at most n times in total, even though there is a loop inside a loop. Each map lookup takes about one step on average.
  • Memory: O(c), where c is the number of different characters the map holds. For plain English letters, that is a small fixed number. The fixed-size and grow-and-shrink versions only keep a few numbers. Their memory is O(1), which means it stays the same however long the input is.

Compare that with checking every run: O(n²) runs, and O(n³) work if you also rescan each run for repeats.

Common mistakes

  • Letting left move backward. In the example, the old a at position 0 is outside the window. If you jump to "last position + 1" without checking, left goes back to 1. The window then holds both bs, and the code answers 7 instead of 6. Use the >= left check, or write left = Math.max(left, last.get(ch) + 1).
  • Off by one on the length. A window from left to right, both included, has right - left + 1 items.
  • Recounting the window. If each step rebuilds a set or a sum from scratch, you are back to slow code. Update the summary with the one item that came in and the one that left.
  • Using a window when numbers can be negative. "Shortest run with a total of at least 7" relies on the total only going up as the window grows. A negative number breaks that, and shrinking can skip the right answer. Those problems need a different tool, such as running totals stored in a map (LeetCode 560, Subarray Sum Equals K).
  • Recording the answer at the wrong moment. For "longest", record after the window is valid again. For "shortest", record while it is still valid, before you shrink past it.
  • Assuming one position is one character. s[i] in JavaScript reads one UTF-16 unit, a piece of how the text is stored. That is fine for the letters, digits and symbols in interview problems. Some emoji take two units, so real-world text may need Array.from(s).

Practice problems

Try these in order. Each one is the same loop with a different rule or summary.

  1. LeetCode 643, Maximum Average Subarray I. A fixed-size window. Keep a running total.
  2. LeetCode 1004, Max Consecutive Ones III. Grow and shrink. The summary is how many zeros are inside.
  3. LeetCode 424, Longest Repeating Character Replacement. Grow and shrink. The summary is a count of each letter.
  4. LeetCode 567, Permutation in String. A fixed-size window that compares letter counts.
  5. LeetCode 438, Find All Anagrams in a String. The same window as 567, but you collect every match.
  6. LeetCode 76, Minimum Window Substring. The hardest one here. Grow until the window has everything you need, then shrink to find the shortest.

In short

A sliding window keeps a run of neighbors and a small summary of what is inside. The right edge reads each item once, and the left edge only moves forward. That makes problems about runs take one pass instead of checking every run.

Want a video for a different problem?

Type a problem, a pattern or a system to design. You get a narrated video like the one above, usually ready in 5 to 9 minutes.

3 free videos with your own AI key. An AI key is a code from an AI company, such as Anthropic or OpenAI. Your own AI account pays for the writing. See pricing

Make a video