Skip to content
Visual explainer 3h to learn 4 steps

Sliding window

Solve substring and subarray problems in O(n) with fixed and variable windows.

By Invicly Tech, , in Data Structures & Algorithms. About 12 minutes to read.

Topic 49 of 54

In short

A sliding window maintains a contiguous range of the input and updates its summary as the range moves, instead of recomputing from scratch. Fixed windows slide one step at a time; variable windows grow the right edge and shrink the left edge while a condition is violated. Each element enters and leaves the window once, so the total is O(n).

Explained simply

A window is a part of an array or string where the items sit next to each other, from a left index to a right index. Questions like "the biggest total of 3 days in a row" or "the longest piece of text with no repeated letter" are window questions.

The slow way tries every start and every end and adds everything up again each time. A sliding window is smarter: when it moves one step, it adds the new item on the right and removes the old item on the left. Think of a train window: as the train moves, one tree comes into view and one leaves.

There are two kinds. A fixed window always has the same size k, like a 7-day moving average. A variable window grows on the right while things are fine and shrinks from the left when a rule is broken, like "no repeated letters".

It is fast because each item enters the window once and leaves at most once. Even with a loop inside a loop, the total work is about 2n steps, which is O(n).

Press Play on a diagram to walk through it one step at a time.

CycleVariable window loop
  1. 1
    Expand

    Add s[right] to the window state.

  2. 2
    Check

    Is the window invalid?

  3. 3
    Shrink

    Remove s[left], left += 1, until valid.

  4. 4
    Record

    Update the best answer.

  5. Back to step 1
FlowFixed window k = 3 over [2, 1, 5, 1, 3, 2]
  1. 1
    First window

    2 + 1 + 5 = 8.

  2. 2
    Slide

    +1 -2 = 7.

  3. 3
    Slide

    +3 -1 = 9.

  4. 4
    Slide

    +2 -5 = 6.

  5. 5
    Best

    9, from [5, 1, 3].

MapWhat should the window remember?
Window state
  • A running sum
    • Moving averages
    • Smallest subarray with sum at least S
  • Character counts
    • Anagrams in a string
    • Minimum window substring
    • At most k distinct
  • Last seen index
    • Longest substring without repeats
  • Monotonic deque
    • Window maximum
    • Window minimum

In depth

When a variable window is allowed

A variable window only works when validity is monotonic. That means: if a window is invalid, every bigger window that contains it is also invalid, and shrinking from the left moves you back toward valid. This is true for "at most k distinct characters", "no repeated characters" and "sum at most S" when all numbers are non-negative.

Negative numbers break it. For "subarray with sum exactly k" on [1, -1, 5, -2, 3], removing an element on the left can make the sum bigger, so the window cannot decide which way to move. The standard fix is prefix sums with a hash map: keep a count of every prefix sum seen so far, and at each index add count[prefix - k] to the answer. That is O(n) time and O(n) space.

  • Non-negative numbers: sliding window is fine
  • Negative numbers: prefix sums plus a hash map
  • Character counts are always non-negative, so string windows are safe

Two templates: longest valid and shortest valid

Almost every variable window problem fits one of two loops. For the longest valid window, add a[right], then shrink while the window is invalid, then record right - left + 1. The answer is recorded when the window is valid and as wide as it can be.

For the shortest valid window, add a[right], then while the window is valid, record its length and shrink from the left. The answer is recorded inside the loop, each time you find a smaller valid window.

Mixing these up is the most common bug: recording in the wrong place gives answers that are off by one or always zero. Before coding, say which template you need. Example: "smallest subarray with sum at least 7" is the shortest-valid template; "longest substring with at most 2 distinct letters" is the longest-valid one.

CompareWhere to record the answer
Longest valid window
  • Add a[right]
  • While invalid: remove a[left]
  • Record after the while loop
  • Answer only grows
Shortest valid window
  • Add a[right]
  • While valid: record, then remove a[left]
  • Record inside the while loop
  • Answer only shrinks

Minimum window substring, step by step

Given s and t, find the shortest part of s that contains every character of t, with repeats counted. Keep need, a Counter of t, and missing, the number of characters still needed (len(t) at the start).

Move right across s. When need[ch] is above 0, this character was really needed, so missing goes down by 1. Always do need[ch] -= 1; negative values mean extra copies. When missing reaches 0, the window covers t. Now shrink: while need[s[left]] is negative, that character is extra, so give it back and move left. The window is now as small as it can be for this right end, so compare it with the best so far.

Then drop s[left] on purpose, which makes missing 1 again, and keep going. Time is O(len(s) + len(t)) and memory is O(size of the alphabet).

FlowMinimum window loop for one right step
  1. 1
    Take s[right]

    If needed, missing -= 1.

  2. 2
    missing == 0?

    No: keep expanding.

  3. 3
    Drop extras

    Shrink while need[s[left]] is negative.

  4. 4
    Record

    Keep it if it is the shortest so far.

  5. 5
    Break cover

    Remove s[left], missing becomes 1.

Counting subarrays and the exactly k trick

Some problems ask how many subarrays satisfy a rule, not the longest one. In the longest-valid template, once the window [left, right] is valid, every subarray that ends at right and starts at left or later is valid too. That is right - left + 1 subarrays, so add it at each step.

Windows handle "at most k" naturally but not "exactly k", because an exactly-k window can be invalid on both sides. The trick: exactly(k) = atMost(k) - atMost(k - 1). For example, the number of subarrays with exactly 2 distinct integers in [1, 2, 1, 2, 3] is atMost(2) - atMost(1) = 12 - 5 = 7. Both calls are O(n), so the whole thing stays O(n).

  • Valid window adds right - left + 1 subarrays ending at right
  • exactly(k) = atMost(k) - atMost(k - 1)

Sliding window maximum with a deque

For the maximum of every window of size k, a running sum does not help, because you cannot "subtract" a maximum. A heap works in O(n log n). A monotonic deque does it in O(n).

The deque holds indexes whose values are in decreasing order. When a new value x arrives, pop from the back every index whose value is at most x: those elements can never be a maximum again, because x is newer and at least as big. Push the new index. If the front index has slid out of the window (index at most i - k), pop it from the front. The front is now the maximum.

Each index is pushed once and popped at most once, so the total is O(n), with O(k) memory. The same idea, with the order flipped, gives the window minimum.

Learn it in 4 short steps

About 45m each. Track them with a timer in your plan.

  1. 1
    Use fixed-size windows for averages~45m
  2. 2
    Grow and shrink variable windows~45m
  3. 3
    Find the longest substring without repeats~45m
  4. 4
    Find the minimum window substring~45m

Key points

  • Time O(n): both pointers only move forward.
  • Window state is usually a sum, count or dict of character frequencies.
  • Longest substring without repeats tracks the last index of each character.
  • Minimum window substring shrinks while all required characters are covered.

Key terms

Tap a card to flip it. 0/3 known

Examples

python
def longest_unique(s):            # O(n)
    last, left, best = {}, 0, 0
    for right, ch in enumerate(s):
        if ch in last and last[ch] >= left:
            left = last[ch] + 1   # shrink past the repeat
        last[ch] = right
        best = max(best, right - left + 1)
    return best

def max_avg(nums, k):             # fixed window
    s = best = sum(nums[:k])
    for i in range(k, len(nums)):
        s += nums[i] - nums[i - k]; best = max(best, s)
    return best / k

Minimum window substring: s = ADOBECODEBANC, t = ABC

Step 1: expand right until A, B and C are all inside. That happens at ADOBEC (missing hits 0); nothing on the left is extra, so record length 6. Step 2: drop A on purpose and keep expanding. The next full cover arrives when the second A is added (DOBECODEBA); shrinking past the extra letters leaves CODEBA, length 6, not better. Step 3: drop C, expand to the final C, and shrink: the window becomes BANC, length 4. That is the answer.

python
from collections import Counter

def min_window(s, t):             # O(len(s) + len(t))
    need, missing = Counter(t), len(t)
    left = start = end = 0
    for right, ch in enumerate(s, 1):   # right is exclusive
        if need[ch] > 0: missing -= 1
        need[ch] -= 1
        if missing == 0:
            while need[s[left]] < 0:
                need[s[left]] += 1; left += 1
            if end == 0 or right - left < end - start:
                start, end = left, right
            need[s[left]] += 1; missing += 1; left += 1
    return s[start:end]

Smallest subarray with sum at least 7 in [2, 3, 1, 2, 4, 3]

All numbers are non-negative, so a variable window is safe, and we want the shortest valid window. Add 2, 3, 1, 2: sum 8 is valid at length 4. Shrink: remove 2, sum 6, invalid. Add 4: sum 10, length 4; remove 3, sum 7, length 3; remove 1, sum 6. Add 3: sum 9, length 3; remove 2, sum 7, length 2 ([4, 3]); remove 4, sum 3. End of array: the answer is 2.

python
def min_len(target, a):           # O(n)
    left = s = 0
    best = float("inf")
    for right, x in enumerate(a):
        s += x
        while s >= target:
            best = min(best, right - left + 1)
            s -= a[left]; left += 1
    return 0 if best == float("inf") else best

print(min_len(7, [2, 3, 1, 2, 4, 3]))   # 2

Quick reference

  • Fixed window: start with sum(a[:k]), then s += a[i] - a[i - k] for i from k to n - 1
  • Longest valid: add a[right], shrink while invalid, then record right - left + 1
  • Shortest valid: add a[right], then while valid record the length and shrink
  • Variable windows need monotonic validity; with negative numbers use prefix sums plus a hash map
  • exactly(k) = atMost(k) - atMost(k - 1); a valid window adds right - left + 1 subarrays
  • Window maximum: deque of indexes with decreasing values, pop stale front, O(n) total
  • Minimum window substring: Counter of t plus a missing count, O(len(s) + len(t))

Common mistakes

  • Recomputing the window sum each step, giving O(n x k).
  • Using sliding window with negative numbers where shrinking does not restore validity.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1What does the fixed sliding window cost for the maximum sum of every size-k window in an array of length n?

Question 2

2Why does a variable window fail for "subarray sum equals k" when numbers can be negative?

Question 3

3How do you count subarrays with exactly k distinct values using windows?

Question 4

4Which structure gives the maximum of every size-k window in O(n) total?

Question 5

5What is the length of the longest substring of "eceba" with at most 2 distinct characters?

0/5 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Return the maximum number of vowels in any substring of s with length k. For s = "abciiidef" and k = 3 the answer is 3.

  2. Exercise 2medium

    Return the length of the longest substring of s that contains at most k distinct characters.

  3. Exercise 3hard

    Return the maximum of every window of size k. [1, 3, -1, -3, 5, 3, 6, 7] with k = 3 gives [3, 3, 5, 5, 6, 7]. Use O(n) time.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

How do I recognise a sliding window problem?
Look for the words contiguous, subarray or substring, together with longest, shortest, at most or count. If the items must sit next to each other, a window is a strong first guess.
Is a nested while loop really O(n)?
Yes. The left pointer only moves forward and can move at most n times in the whole run, so the inner loop does at most n steps in total, not n per outer step.
Why is my window answer off by one?
Usually the window length is computed as right - left instead of right - left + 1 for inclusive indexes, or the answer is recorded in the wrong template position. Trace a two-element input by hand to check.

Go deeper

ShareXLinkedInWhatsApp