Skip to content

Pattern · Interview prep

Sliding Window

Keep a moving slice of an array or string and update it as its ends move, instead of rescanning from every starting point.

What it is

What is the sliding window pattern?

A sliding window is a contiguous segment of the input. You grow it on the right and shrink it on the left so it keeps a property, such as “no repeated characters” or “exactly k items”. Each element enters the window once and leaves once, so you never restart from each starting index.

  • Fixed size. The window is always k wide. Add the new element, drop the old one.
  • Variable size. The window grows until a rule breaks, then shrinks until it holds again.
Array, window size 3
window sum7

Slide one step: add 3, drop 1 → 9

WindowEnters nextLLeft endRRight end

When to use it

How do you recognize a sliding window problem?

Read the statement for these signals before you reach for code.

Read the full recognition guide: How to recognize a sliding window problem

Phrases to watch for

  • contiguous subarray or substring
  • longest or shortest segment
  • at most K
  • without repeating
  • window of size k
  • maintain a property while expanding and shrinking
  • optimize a range
  1. 1

    The answer is a contiguous slice

    The problem asks about a subarray or substring, so the elements must sit next to each other.

  2. 2

    You want the longest or shortest segment

    The goal is a length or a best sum over a segment that satisfies a rule.

  3. 3

    One step in, one step out

    You can update the answer by adding the new element and removing the one that left.

Looks similar, but isn’t

  • Subsequences, not slices

    If elements may be skipped, a window will miss answers. Think Dynamic Programming.

  • A pair in a sorted list

    Two ends closing in on a target is Two Pointers, not a moving slice.

  • Sum equals k with negatives

    Shrinking stops being safe when values go negative. Try Prefix Sum with a Hash Map.

Worked example

How does it work on the longest substring without repeating characters?

Given a string, return the length of the longest stretch with no repeated character. It is a classic variable-size window, and one of the problems you can practice below.

TypeScriptlengthOfLongestSubstring
function lengthOfLongestSubstring(s: string): number {  const lastSeen = new Map<string, number>();  let left = 0;  let best = 0;   for (let right = 0; right < s.length; right++) {    const ch = s[right];    const prev = lastSeen.get(ch);     // A repeat inside the window: move left past it.    if (prev !== undefined && prev >= left) {      left = prev + 1;    }     lastSeen.set(ch, right);    best = Math.max(best, right - left + 1);  }   return best;}

The only place the window shrinks.

Code is shown in TypeScript. You can solve problems in TypeScript, JavaScript, or Python.

Complexity

  • TimeO(n)

    Each index enters the window once, and left never moves back.

  • SpaceO(k)

    k is the number of distinct characters stored in the map.

Fixed-size variant

When the width is a fixed k, drop the shrinking rule. Add nums[right], subtract nums[right - k], and keep the best total.

Why the map stores an index

Storing the last index lets left jump straight past a repeat in one move, instead of shrinking one character at a time.

Step by step on abcabcbb

  1. 1

    Start with left = 0 and an empty lastSeen map. Move right one character at a time and record where each character was last seen.

  2. 2

    right reaches c at index 2. The characters a, b and c are all new, so the window grows to abc and best = 3.

  3. 3

    right hits a at index 3. It was last seen at index 0, inside the window, so left jumps to 1. The window is bca, still length 3.

  4. 4

    b and c repeat the same way. left moves to 2, then 3, and the window slides along as cab, then abc.

  5. 5

    At index 6, b was last seen at 4, so left becomes 5. At index 7 another b (seen at 6) pushes left to 7. The window is now just b.

  6. 6

    Return best = 3. right visited each index once and left only ever moved forward, so the total work is O(n).

Common mistakes

What mistakes do people make with sliding window?

  • Restarting the window at every start index

    Rescanning from each left end turns one pass into O(n²) and throws away work you already did.

    InsteadKeep one window and move its ends forward. Update the state instead of rebuilding it.

  • Shrinking too far

    Moving left past the repeat, or past the point the rule is satisfied again, can skip a longer valid window.

    InsteadShrink only while the rule is broken, and stop the moment it holds again.

  • Trusting a stale lookup

    A hash map can remember a character from before the window began. Using that index drags left backwards.

    InsteadCompare the stored index with left first. Only an index inside the window counts.

  • Off-by-one on the length

    Window length is right − left + 1. Dropping the +1 makes every answer one too small.

    InsteadWrite the length formula once, and check it on a window of size 1.

Practice it in Algofily

Which Algofily problems train sliding window?

4 problems are tagged Sliding Window. They run from a fixed-width sum up to a hard covering window.

A lock means the problem opens after you create an account. Pair With Target is open to try without one.

Start Learning.

Work Pair With Target through all seven stages. An account saves that progress and opens every other problem.