AlgoViz

Sliding window (variable size)

medium 20 min

A variable sliding window keeps a contiguous range [left, right] that grows on the right to explore and shrinks on the left whenever a validity rule breaks.

Video lesson · Chapter 1 of 7

The wristband scanner

0:00 / 4:12

Longest window

1:19Reel

More reels

One idea each, a minute or less.

Play all in Bytesized Learning

Shortest window

1:18Reel

Window with a frequency map

1:16Reel

Minimum window substring

1:15Reel

Exactly K

1:16Reel

How it works

Step through the idea, or press Play.

Step 1 of 3

Grow right. Add s[right] to the window state: a set, a counts map or a running sum

Understand it

Start here

Recap: a window that changes size

  • Fixed window

    Width kk never changes: add one value on the right, drop one on the left. See Sliding window (fixed size).

  • Two pointers

    Two indexes that only move forward. The variable window is the reader/writer shape with a state between them. See Two pointers.

  • Hash maps and sets

    The window's state is usually a set of what is inside or a map of counts, each update O(1)O(1). See Hash usage.

In a variable window nobody tells you the width. The problem gives a rule instead, such as "no repeated characters" or "sum at least 7", and asks for the longest or shortest contiguous range that obeys it. Classic example: the longest substring of "abcabcbb" without repeating characters is "abc", length 3.

The template

Grow right, shrink left, then record

right walks every index once in a for loop and adds s[right] to the state. If that broke the rule, a while loop removes s[left] and moves left up until the window is valid again. Then the window [left, right] is the best window that ends at right, so compare its length, right−left+1\text{right} - \text{left} + 1, with the best so far.

One turn of the loop

The inner loop runs zero or more times per step, but left never moves back.
Python
def longest_valid(items):    state = make_state()            # set, counts map, running sum...    left = 0    best = 0    for right in range(len(items)):        add(state, items[right])            # 1. EXPAND        while not valid(state):            remove(state, items[left])      # 2. SHRINK            left += 1        best = max(best, right - left + 1)  # 3. UPDATE (window is valid)    return best
The universal template. Only add, remove and valid change between problems.
The expand-shrink dance
  1. 1EXPANDright++, add the new item
  2. 2SHRINKwhile invalid: remove s[left], left++
  3. 3UPDATEtrack the best valid window
Repeat: back to EXPAND

Why it is safe

The validity condition must be monotone

The template throws away every window that starts before the new left. That is only safe if a window that is invalid cannot become valid by growing on the right. For "at most" rules this holds: adding a character never removes a repeat, and adding a non-negative number never lowers a sum.

Monotone validity

[L,R] valid  ⟹  [L′,R′] valid for all L≤L′≤R′≤R[L, R] \text{ valid} \;\Longrightarrow\; [L', R'] \text{ valid for all } L \le L' \le R' \le R
Every piece of a valid window is valid. Equivalently: if [L,R][L, R] is invalid, so is [L,R+1][L, R+1], so once left is pushed past LL no window starting at LL is ever needed again.

What the state is and when the window is valid

ProblemStateValid whenRecord
Longest substring without repeatsset (or last-index map)s[right] not already insidelongest, after shrinking
Longest with at most k distinctcounts maplen(counts) <= klongest, after shrinking
Minimum size subarray sumrunning totaltotal >= target is the goalshortest, inside the loop
Minimum window substringwindow counts, havehave == required is the goalshortest, inside the loop
Two families: keep the window valid and grow it (longest), or make it valid and squeeze it (shortest).

Example 1

Longest substring without repeating characters

State: a set of the characters inside the window. When s[right] is already in the set, the window would hold a repeat, so remove characters from the left until the old copy is gone, then add s[right]. On "abcabcbb" the window grows to abc, then slides as bca, cab, abc, and shrinks to cb and b at the end. Best: 3.

Trace on "abcab"

rightcharActionleftWindowSetbest
0aadd0a{a}1
1badd0ab{a, b}2
2cadd0abc{a, b, c}3
3arepeat: drop a, then add1bca{b, c, a}3
4brepeat: drop b, then add2cab{c, a, b}3
The window never holds a repeat after the shrink, so its length is always a legal candidate.
Python
def longest_unique(s):    seen = set()    left = 0    best = 0    for right in range(len(s)):        while s[right] in seen:      # repeat: shrink from the left            seen.remove(s[left])            left += 1        seen.add(s[right])           # expand        best = max(best, right - left + 1)    return bestfor s in ["abcabcbb", "bbbbb", "abcdef", "pwwkew", "aab", ""]:    print(repr(s), longest_unique(s))   # 3 1 6 3 2 0
Set version: each character is added once and removed at most once.
Edit and run it in your browser

What happens to one new character

On "abba" the second b removes a and then b: left jumps from 0 to 2.

Example 1, faster

Last-index map: jump left instead of crawling

Instead of a set, store where each character was last seen. When s[right] was seen at index jj inside the window (j≥leftj \ge \text{left}), the window must start after it, so set left = j + 1 in one jump. Same O(n)O(n) bound, but each step does O(1)O(1) work instead of a crawl.

Python
def longest_unique(s):    last = {}                    # char -> index where it was last seen    left = 0    best = 0    for right, ch in enumerate(s):        if ch in last and last[ch] >= left:            left = last[ch] + 1  # jump past the old copy        last[ch] = right        best = max(best, right - left + 1)    return bestprint(longest_unique("abba"))      # 2print(longest_unique("tmmzuxt"))   # 5  ("mzuxt")
The last-index version. The >= left check is the whole trick.
Edit and run it in your browser
VersionHow left movesTimeSpaceWatch for
Setcrawls one step at a timeO(n)O(n) amortisedO(min⁡(n,σ))O(\min(n, \sigma))use while, not if
Last-index mapjumps to last[ch] + 1O(n)O(n), no inner loopO(min⁡(n,σ))O(\min(n, \sigma))stale entries: check >= left
σ\sigma is the alphabet size: 26 for lowercase letters, 128 for ASCII.

Example 2

Minimum size subarray sum: the shortest valid window

Given positive numbers and a target, find the shortest contiguous subarray whose sum is at least target. Now validity is the goal, not the constraint: grow until total >= target, then shrink as far as possible while it stays true, recording the length before each removal. On [2, 3, 1, 2, 4, 3] with target 7 the lengths found are 4, 4, 3, 3 and finally 2 for [4, 3].

Where to record: longest versus shortest

Shortest windows are recorded inside the shrink loop, because the last removal makes the window invalid.
Python
def min_subarray_len(target, nums):    left = 0    total = 0    best = float("inf")    for right in range(len(nums)):        total += nums[right]                  # expand        while total >= target:                # still good: try smaller            best = min(best, right - left + 1)            total -= nums[left]            left += 1    return 0 if best == float("inf") else bestprint(min_subarray_len(7, [2, 3, 1, 2, 4, 3]))   # 2print(min_subarray_len(4, [1, 4, 4]))            # 1print(min_subarray_len(11, [1, 1, 1, 1]))        # 0
Shortest window with sum at least target. Needs non-negative numbers.
Edit and run it in your browser

Example 3

Longest substring with at most k distinct characters

State: a counts map of the characters inside. The window is valid while len(counts) <= k. When a new character makes it k+1k + 1, crawl left forward, decrementing counts, and delete a key when its count hits 0 so that len(counts) stays honest. On "araaci" with k=2k = 2 the best is "araa", length 4; on "eceba" it is "ece", length 3.

Python
def longest_k_distinct(s, k):    counts = {}    left = 0    best = 0    for right, ch in enumerate(s):        counts[ch] = counts.get(ch, 0) + 1        while len(counts) > k:            # too many kinds: shrink            out = s[left]            counts[out] -= 1            if counts[out] == 0:                del counts[out]           # keep len(counts) honest            left += 1        best = max(best, right - left + 1)    return bestprint(longest_k_distinct("araaci", 2))   # 4print(longest_k_distinct("eceba", 2))    # 3print(longest_k_distinct("aa", 0))       # 0
Counts map version. Also solves Fruit Into Baskets (k = 2).
Edit and run it in your browser

Trace on "araaci", k = 2

rightcharcounts after shrinkleftWindowbest
0a{a: 1}0a1
1r{a: 1, r: 1}0ar2
2a{a: 2, r: 1}0ara3
3a{a: 3, r: 1}0araa4
4c{a: 2, c: 1}2aac4
5i{c: 1, i: 1}4ci4
At c, three kinds: drop a (count 2), then r (count 0, deleted). At i, drop two more as.

Example 4

Minimum window substring: need and have

Find the shortest substring of s that contains every character of t, with multiplicity. need counts t. window counts the current range. have is how many distinct characters already meet their need, and the window is good when have == required, where required = len(need). On s = "ADBECFEBAC", t = "ABC" the windows found are ADBEC (5), EBAC (4) and finally `BAC` (3).

Keeping have in step with the counts

have changes only when a count crosses its need, so checking validity is O(1)O(1) instead of comparing two maps.
Python
from collections import Counterdef min_window(s, t):    if not t:        return ""    need = Counter(t)    required = len(need)     # distinct characters to satisfy    have = 0                 # how many are satisfied now    window = {}    left = 0    best_len, best_left = float("inf"), 0    for right, ch in enumerate(s):        window[ch] = window.get(ch, 0) + 1        if ch in need and window[ch] == need[ch]:            have += 1        while have == required:              # good: squeeze it            if right - left + 1 < best_len:                best_len, best_left = right - left + 1, left            out = s[left]            window[out] -= 1            if out in need and window[out] < need[out]:                have -= 1            left += 1    return "" if best_len == float("inf") else s[best_left:best_left + best_len]print(min_window("ADBECFEBAC", "ABC"))      # BACprint(min_window("ADOBECODEBANC", "ABC"))   # BANCprint(min_window("a", "aa"))                # (empty)
Minimum window substring in O(∣s∣+∣t∣)O(|s| + |t|).
Edit and run it in your browser

Complexity

Why it is O(n): each index enters once and leaves once

The while inside the for looks like O(n2)O(n^2), but count pointer moves instead of loop nesting. right moves nn times. left starts at 0, only increases, and never passes nn, so across the whole run it moves at most nn times. Each move does O(1)O(1) work on a set, a map or a sum.

Amortised count

T(n)=∑R=0n−1(1+sR)=n+∑R=0n−1sR  ≤  n+n=2n=O(n)T(n) = \sum_{R=0}^{n-1} \big(1 + s_R\big) = n + \sum_{R=0}^{n-1} s_R \;\le\; n + n = 2n = O(n)
sRs_R is the number of shrinks done at step RR. One step can shrink a lot, but the shrinks across all steps add up to the total distance left travels, at most nn.

Against brute force

n(n+1)2⏟every substring×O(n)⏟check it=O(n3)⟶O(n2) with a running set⟶O(n) with the window\underbrace{\frac{n(n+1)}{2}}_{\text{every substring}} \times \underbrace{O(n)}_{\text{check it}} = O(n^3) \quad\longrightarrow\quad O(n^2) \text{ with a running set} \quad\longrightarrow\quad O(n) \text{ with the window}
For "abcabcbb" (n=8n = 8) brute force looks at 36 substrings; the window makes 8 right moves and 7 left moves, 15 in total. Space is the state: O(min⁡(n,σ))O(\min(n, \sigma)) for a set or map, O(1)O(1) for a sum.

Limits

When it fails: negative numbers need prefix sums

With negatives the sum is no longer monotone: growing can lower it and shrinking can raise it. Take [5, -10, 4, 3] with target 7. The running sums are 5, −5, −1, 2, never 7 or more, so the window never shrinks and returns 0, yet [4, 3] sums to exactly 7. The −10 is stuck inside, and nothing in the rule says to drop it.

Window or prefix sums?

"Exactly" rules are not monotone either, but they can often be written as the difference of two "at most" windows.

The prefix-sum rewrite

P0=0,Pi+1=Pi+ai,sum(aL,…,aR)=PR+1−PLP_0 = 0,\quad P_{i+1} = P_i + a_i, \qquad \text{sum}(a_L, \dots, a_R) = P_{R+1} - P_L
"Subarray sums to kk" becomes "find an earlier prefix equal to PR+1−kP_{R+1} - k", one hash lookup per index whatever the signs. See Prefix sums.
Python
def count_sum_k(nums, k):    seen = {0: 1}          # prefix sum -> how many times seen    prefix = 0    count = 0    for x in nums:        prefix += x        count += seen.get(prefix - k, 0)        seen[prefix] = seen.get(prefix, 0) + 1    return countprint(count_sum_k([5, -10, 4, 3], 7))    # 1  ([4, 3])print(count_sum_k([1, -1, 1, -1], 0))    # 4
Count subarrays summing to k, negatives allowed.
Edit and run it in your browser

Patterns

The family of variable-window problems

ProblemTypeStateNotes
Longest substring without repeatslongestset or last indexThe first one to learn
Longest with at most k distinctlongestcounts mapFruit Into Baskets is k = 2
Longest repeating character replacementlongestcounts + max countValid while length - maxCount <= k
Max consecutive ones with k flipslongestcount of zerosValid while zeros <= k
Minimum size subarray sumshortestrunning sumPositive numbers only
Minimum window substringshortestneed, window, haveRecord inside the loop
Subarrays with product below kcountrunning productAdd right - left + 1 per step
Counting problems add the number of valid windows ending at right, which is right - left + 1.

Do

  • Write the validity rule in words before coding.
  • Use a while to shrink, not an if: one removal may not be enough.
  • Delete map keys whose count reaches 0 when you use len(counts).
  • Record longest after shrinking; record shortest inside the shrink loop.
  • Check the signs: negatives in a sum mean prefix sums.

Don't

  • Recompute the window's set or sum from scratch on each step.
  • Let left move backwards (stale last-index entries).
  • Use the window for subsequences: it only handles contiguous ranges.
  • Return infinity, or start a minimum at 0.
  • Forget the empty input and the case where no window is ever valid.

Recap

Key takeaways

Key points

  • A variable window grows on the right and shrinks on the left to keep a validity rule.
  • It works when the rule is monotone: a broken window cannot be fixed by growing.
  • Template: for right, add; while invalid, remove s[left] and left += 1; record.
  • Longest: record after shrinking. Shortest: record inside the shrink loop before each removal.
  • State is a set, a last-index map, a counts map or a running sum, all O(1) per update.
  • Minimum window substring tracks need, window counts and have == required.
  • Each index enters once and leaves at most once: at most 2n moves, O(n) amortised.
  • Negatives break sum windows: switch to prefix sums with a hash map or a monotonic deque.

Sources