Simple Algorithm
Algorithms & Data Structures · Optimized · 22 min

The Sliding Window Technique

Fixed and variable windows: from all O(n²) subarrays to a single pass.

An array of a million elements has about 5×10115\times10^{11} subarrays, yet a single left-to-right pass of two indices visits every one that matters. The window never moves backward, so the whole scan costs at most 2n2n pointer moves. The art lies in choosing the state the window carries, and in knowing when the trick is valid at all.

What you’ll learn

  • Maintain a fixed-size window with one entering and one leaving element per step, including windows of letter counts.
  • Write the grow-right, shrink-left template for the longest and the shortest valid window, keeping sums and counts incrementally.
  • Justify correctness from a monotone validity rule and the O(n)O(n) bound by amortization.
  • Recognize window problems, reject the look-alikes (negative numbers, subsequences, "exactly kk"), and avoid the stale-state and off-by-one bugs.

Fixed windows: one in, one out

"The largest sum of kk consecutive elements": the brute force sums each of the n−k+1n-k+1 windows from scratch, Θ(nk)\Theta(nk) additions. But consecutive windows share k−1k-1 elements. When the window slides from a[r−k..r−1]a[r-k..r-1] to a[r−k+1..r]a[r-k+1..r] (inclusive), exactly one element enters and one leaves:

sum(r−k+1..r)=sum(r−k..r−1)+a[r]−a[r−k].\text{sum}(r-k+1..r)=\text{sum}(r-k..r-1)+a[r]-a[r-k].
python
def best_window_sum(a, k):
    """Largest sum of k consecutive elements (1 <= k <= len(a))."""
    s = sum(a[:k])                     # the first window, a[0..k-1]
    best = s
    for r in range(k, len(a)):         # window a[r-k+1..r]: a[r] enters, a[r-k] leaves
        s += a[r] - a[r - k]
        best = max(best, s)
    return best

print(best_window_sum([4, 8, -2, 6, 3, 4, 2, -5, 8, 5, -6, 4], 3))   # 13

Θ(n)\Theta(n) time in the worst case, O(1)O(1) extra space. Negative values are fine here: a fixed window has no validity rule that they could break.

The state need not be a sum. "Does ss contain a rearrangement (a permutation) of pp?" slides a window of length ∣p∣\abs{p} over ss and keeps the count of each letter inside. Recounting 26 letters per step would be slow, so keep one more number: how many of the 26 letters have the right count. Each step changes two counts, and each change can flip that number by at most 1.

python
def contains_permutation(p, s):
    """Does some window of s of length len(p) hold exactly the letters of p? Lowercase a-z."""
    k = len(p)
    if k > len(s):
        return False
    need, have = [0] * 26, [0] * 26
    for c in p:
        need[ord(c) - 97] += 1
    for c in s[:k]:
        have[ord(c) - 97] += 1
    matches = sum(need[i] == have[i] for i in range(26))   # letters whose counts agree
    for r in range(k, len(s)):
        if matches == 26:
            return True
        for c, d in ((s[r], 1), (s[r - k], -1)):           # s[r] enters, s[r-k] leaves
            i = ord(c) - 97
            matches -= need[i] == have[i]
            have[i] += d
            matches += need[i] == have[i]
    return matches == 26

print(contains_permutation("tol", "hellotoyou"))   # True: the window "lot"

O(∣s∣+∣Σ∣)O(\abs{s}+\abs{\Sigma}) time for an alphabet Σ\Sigma of 26 letters, instead of O(∣s∣⋅∣Σ∣)O(\abs{s}\cdot\abs{\Sigma}) for comparing all counts at every step.

Variable windows: grow right, shrink left

Most window problems have no fixed length: "the longest subarray with at most kk distinct values". A variable window a[L..R]a[L..R] follows one template. For each RR, let a[R]a[R] enter; while the window breaks the rule, let a[L]a[L] leave and advance LL; then a[L..R]a[L..R] is the longest valid window that ends at RR.

The template needs a state that supports add, remove and an O(1)O(1) is it valid? test. For distinct values, that is a map from value to count, where a value disappears from the map when its count drops to 0.

python
from collections import defaultdict

def longest_at_most_k_distinct(a, k):
    count = defaultdict(int)           # value -> copies inside a[L..R]
    L = best = 0
    for R, x in enumerate(a):
        count[x] += 1                  # a[R] enters
        while len(count) > k:          # invalid: shrink from the left
            count[a[L]] -= 1
            if count[a[L]] == 0:
                del count[a[L]]        # so len(count) = distinct values inside
            L += 1
        best = max(best, R - L + 1)    # a[L..R] is the longest valid window ending at R
    return best

print(longest_at_most_k_distinct([4, 1, 3, 1, 1, 4, 4, 4, 1, 2, 3, 2], 2))   # 6

For "longest substring without a repeated character" the shrink loop can be a single jump: remember where each character was last seen and move LL just past the earlier copy. The jump must never go backward, because that earlier copy may already lie left of LL.

python
def longest_unique(s):
    last = {}                          # character -> index of its latest occurrence
    L = best = 0
    for R, c in enumerate(s):
        if c in last:
            L = max(L, last[c] + 1)    # jump past the earlier copy, never backward
        last[c] = R
        best = max(best, R - L + 1)
    return best

print(longest_unique("twopointertricks"), longest_unique("abba"))   # 7 2
Check your understanding

In longest_unique, replace L = max(L, last[c] + 1) with L = last[c] + 1 and run it on "abba". What happens?

  1. Nothing changes: it still returns 2
  2. At the final 'a', LL moves back to 1 and the function returns 3, counting "bba"
  3. It raises an error at the second 'b'
  4. It returns 4
Show the answer

B. At the final 'a', LL moves back to 1 and the function returns 3, counting "bba"

After "abb", L=2L=2. The final 'a' was last seen at index 0, so the buggy line sets L=1L=1, moving the window back over the second 'b': "bba" holds 'b' twice, yet its length 3 is recorded. With the max, LL stays at 2 and the answer is 2.

Shortest windows: shrink while still valid

The mirror problem asks for the shortest valid window, where validity survives growing the window: "the shortest subarray with sum at least SS", with positive values. For each RR, let a[R]a[R] enter; then, while the window is valid, record its length and let a[L]a[L] leave. The answer is recorded inside the loop, because the loop stops at the first invalid window.

python
def shortest_sum_at_least(a, S):
    """Length of the shortest subarray with sum >= S (all a[i] > 0), or 0 if there is none."""
    L = s = 0
    best = float('inf')
    for R, x in enumerate(a):
        s += x
        while s >= S:                  # valid: record it, then try a shorter one
            best = min(best, R - L + 1)
            s -= a[L]
            L += 1
    return 0 if best == float('inf') else best

print(shortest_sum_at_least([4, 1, 4, 2, 1, 6, 2, 6, 1, 4, 3, 2], 12))   # 3

The classic hard case is the smallest window of ss that covers tt, every character of tt with its multiplicity. The state is a count of what is still needed and one number, missing, of characters of tt not yet covered; the window is valid exactly when missing is 0.

python
from collections import Counter

def min_window(s, t):
    """Shortest substring of s containing every character of t (with multiplicity), or ''."""
    need = Counter(t)                  # copies still wanted; negative = surplus inside
    missing = len(t)                   # characters of t not yet covered by s[L..R]
    L, best = 0, (float('inf'), 0, 0)
    for R, c in enumerate(s):
        if need[c] > 0:
            missing -= 1
        need[c] -= 1
        while missing == 0:            # valid: record, then shrink
            if R - L + 1 < best[0]:
                best = (R - L + 1, L, R + 1)
            need[s[L]] += 1
            if need[s[L]] > 0:
                missing += 1           # removing s[L] broke the cover
            L += 1
    return s[best[1]:best[2]]

print(min_window("thequickbrownfox", "ofk"))   # kbrownf

Each character enters once and leaves at most once: O(∣s∣+∣t∣)O(\abs{s}+\abs{t}) expected time with a hash map, worst case with an array over a fixed alphabet.

Why one pass suffices

Both templates rest on one property of the rule. Call a validity rule hereditary if every sub-window of a valid window is valid ("at most kk distinct values", "no repeated letter", "sum ≤S\le S with non-negative values"), and upward closed if every super-window of a valid window is valid ("sum ≥S\ge S with positive values", "covers every letter of tt").

DerivationProof sketch and cost
  1. lo(r) ≤ lo(r+1)\mathrm{lo}(r)\ \le\ \mathrm{lo}(r+1)

    Starts only move right. If a[l..r+1]a[l..r+1] is valid, so is its sub-window a[l..r]a[l..r]; every valid start for r+1r+1 is a valid start for rr:

  2. L = min⁡{ l≥L: a[l..r] valid } = lo(r)L\ =\ \min\{\,l\ge L:\ a[l..r]\ \text{valid}\,\}\ =\ \mathrm{lo}(r)

    The loop stops at the right place. When R=rR=r arrives, L=lo(r−1)≤lo(r)L=\mathrm{lo}(r-1)\le\mathrm{lo}(r). The valid starts for rr form the block [lo(r),r][\mathrm{lo}(r),r], so "shrink while invalid" stops exactly at its left end:

  3. #moves ≤ n+n = 2n\#\text{moves}\ \le\ n+n\ =\ 2n

    Cost. RR moves nn times and LL at most nn times, never backward, and each move does one state update. With arrays over a small alphabet that is Θ(n)\Theta(n) worst case; with hash maps, O(n)O(n) expected. A single shrink phase can be long, but the total cannot exceed nn: O(1)O(1) amortized per element.

"The longest run of 1s if you may flip at most kk zeros" is a window in disguise: flipping is never needed outside the window, so the rule is "at most kk zeros inside", which is hereditary. The contest version of the template in C++, for the longest window with sum ≤S\le S over non-negative values:

cpp
#include <algorithm>
#include <cstdio>
#include <vector>
using namespace std;

int main() {
    int n;
    long long S;
    if (scanf("%d %lld", &n, &S) != 2) return 0;
    vector<long long> a(n);
    for (auto &x : a) scanf("%lld", &x);          // all a[i] >= 0
    long long sum = 0;                            // sum of the window a[L..R]
    int best = 0;
    for (int L = 0, R = 0; R < n; R++) {
        sum += a[R];                              // a[R] enters
        while (L <= R && sum > S) sum -= a[L++];  // shrink until valid; may empty it
        best = max(best, R - L + 1);
    }
    printf("%d\n", best);
}

long long sums, and the guard L <= R: without it, a negative SS would let LL run past the end of the array.

Predict before you look

The bits are [1,1,0,0,1,1,1,0,1,1][1,1,0,0,1,1,1,0,1,1] and you may flip at most k=2k=2 zeros. How long is the longest run of 1s you can make?

Show the answer

7 bits

The longest window with at most two zeros has length 7: indices 0–6 (flip the zeros at 2 and 3) or indices 3–9 (flip those at 3 and 7). Every window of length 8 contains three zeros.

Recognizing it

Reach for a sliding window when you see these signals:

  • Contiguity: "subarray", "substring", "consecutive days", "a run of".
  • A best or a count over those stretches: longest, shortest, maximum sum of length kk, number of stretches with a property.
  • A rule that is monotone: ask "if a stretch is valid, is every shorter piece valid?" (longest) or "is every longer stretch valid?" (shortest). If neither holds, a window is the wrong tool.
  • Constraints around n≤105n\le10^5 to 10710^7, where O(n2)O(n^2) stretches are too many but one pass fits.
Problem (in brief)Window state and ruleCost
Longest substring without a repeated characterlast-seen index; L=max⁡(L,last[c]+1)L=\max(L,\text{last}[c]+1)O(n)O(n)
Shortest subarray with sum ≥S\ge S, positive valuesrunning sum; shrink while the sum stays ≥S\ge SO(n)O(n)
Longest subarray with at most kk distinct valuescounts in a map; shrink while more than kk keysO(n)O(n) expected
Smallest window of ss covering every character of ttneeded counts and a missing counter; shrink while coveredO(∣s∣+∣t∣)O(\abs{s}+\abs{t})
Does ss contain a rearrangement of pp?fixed window of length ∣p∣\abs{p}; letter counts and a match counterO(∣s∣+∣Σ∣)O(\abs{s}+\abs{\Sigma})
Five classic window problems; "at most kk flips" and "maximum sum of kk consecutive values" are close relatives.
Check your understanding

Find the length of the shortest subarray with sum at least KK, where values may be negative and n=105n=10^5. Which approach is correct and fast?

  1. The shortest-window template: shrink while the sum stays ≥K\ge K
  2. Sort the array, then use two pointers
  3. Prefix sums with a monotonic deque of candidate start positions
  4. Prefix sums with a hash map of earlier prefix values
Show the answer

C. Prefix sums with a monotonic deque of candidate start positions

With P[0]=0P[0]=0 and P[i+1]=P[i]+a[i]P[i+1]=P[i]+a[i], you want the largest l<rl<r with P[l]≤P[r]−KP[l]\le P[r]-K. A deque of starts with increasing PP values discards dominated starts and answers each rr in O(1)O(1) amortized: O(n)O(n) in all.

Key takeaways

  • A fixed window updates its state with one entering and one leaving element: Θ(n)\Theta(n) instead of Θ(nk)\Theta(nk), with counts and a match counter for anagram-style windows.
  • The variable template grows RR every step and shrinks LL while the window is invalid (longest) or while it stays valid (shortest), updating sums, counts or last-seen positions incrementally.
  • The template is correct exactly when the rule is monotone (hereditary for longest windows, upward closed for shortest), and it costs O(n)O(n) because each index enters once and leaves at most once.
  • Recognize contiguity plus a monotone rule; send sum rules with negative values to prefix sums, subsequences to dynamic programming, and "exactly kk" to a difference of two "at most" windows.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

In the template for the shortest valid window, where must the answer be recorded?

  1. After the shrink loop ends
  2. Inside the shrink loop, before a[L]a[L] leaves
  3. Before a[R]a[R] enters
  4. Once, after the last RR
Show the answer

B. Inside the shrink loop, before a[L]a[L] leaves

The shrink loop runs while the window is valid and stops at the first invalid one. Each valid window must be measured before a[L]a[L] leaves; after the loop, the window is too short to be valid.

Question 2

A single iteration of the outer loop may run the inner shrink loop nn times. Why is the whole scan still O(n)O(n)?

  1. The inner loop runs at most once per outer iteration on average inputs
  2. LL only moves forward, so all the shrink loops together advance it at most nn times
  3. Hash maps make every iteration O(1)O(1)
  4. The window length is bounded by kk
Show the answer

B. LL only moves forward, so all the shrink loops together advance it at most nn times

Count moves instead of iterations: RR moves nn times and LL at most nn times, so there are at most 2n2n moves in total, each followed by O(1)O(1) work. That is an amortized bound, valid for every input.

Question 3

What is the length of the longest subsequence (not necessarily contiguous) of a string with no repeated character?

  1. The answer of the sliding window longest_unique
  2. It needs dynamic programming over prefixes
  3. The number of distinct characters in the string
  4. The length of the string
Show the answer

C. The number of distinct characters in the string

A subsequence can skip anything, so pick one copy of each distinct character, in order. Windows only apply when the elements must be consecutive: "subarray" and "substring" are the signal words, "subsequence" is not.

Question 4

You must count the subarrays with exactly kk distinct values. Which approach is correct?

  1. One window that shrinks while it has more than kk distinct values, adding 1 whenever it has exactly kk
  2. Prefix sums of the values with a hash map
  3. Sort the array, then count runs
  4. Count the subarrays with at most kk distinct values, then subtract those with at most k−1k-1
Show the answer

D. Count the subarrays with at most kk distinct values, then subtract those with at most k−1k-1

"At most kk" is hereditary, so a window counts it in O(n)O(n) by adding R−L+1R-L+1 for every RR. Subarrays with exactly kk distinct values are those with at most kk but not at most k−1k-1, and the second set is inside the first.

Go deeper

Further reading

  • A. Laaksonen, Competitive Programmer's Handbook (2018, free online), §8.1 (the two pointers method on subarrays) and §8.3 (sliding window minimum).
  • S. Halim, F. Halim & S. Effendy, Competitive Programming 4 (2020).