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 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 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 bound by amortization.
- Recognize window problems, reject the look-alikes (negative numbers, subsequences, "exactly "), and avoid the stale-state and off-by-one bugs.
Fixed windows: one in, one out
"The largest sum of consecutive elements": the brute force sums each of the windows from scratch, additions. But consecutive windows share elements. When the window slides from to (inclusive), exactly one element enters and one leaves:
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)) # 13time in the worst case, 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 contain a rearrangement (a permutation) of ?" slides a window of length over 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.
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"time for an alphabet of 26 letters, instead of 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 distinct values". A variable window follows one template. For each , let enter; while the window breaks the rule, let leave and advance ; then is the longest valid window that ends at .
The template needs a state that supports add, remove and an 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.
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)) # 6For "longest substring without a repeated character" the shrink loop can be a single jump: remember where each character was last seen and move just past the earlier copy. The jump must never go backward, because that earlier copy may already lie left of .
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 2In longest_unique, replace L = max(L, last[c] + 1) with L = last[c] + 1 and run it on "abba". What happens?
- Nothing changes: it still returns 2
- At the final 'a', moves back to 1 and the function returns 3, counting "bba"
- It raises an error at the second 'b'
- It returns 4
Show the answer
B. At the final 'a', moves back to 1 and the function returns 3, counting "bba"
After "abb", . The final 'a' was last seen at index 0, so the buggy line sets , moving the window back over the second 'b': "bba" holds 'b' twice, yet its length 3 is recorded. With the max, 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 ", with positive values. For each , let enter; then, while the window is valid, record its length and let leave. The answer is recorded inside the loop, because the loop stops at the first invalid window.
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)) # 3The classic hard case is the smallest window of that covers , every character of with its multiplicity. The state is a count of what is still needed and one number, missing, of characters of not yet covered; the window is valid exactly when missing is 0.
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")) # kbrownfEach character enters once and leaves at most once: 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 distinct values", "no repeated letter", "sum with non-negative values"), and upward closed if every super-window of a valid window is valid ("sum with positive values", "covers every letter of ").
Starts only move right. If is valid, so is its sub-window ; every valid start for is a valid start for :
The loop stops at the right place. When arrives, . The valid starts for form the block , so "shrink while invalid" stops exactly at its left end:
Cost. moves times and at most times, never backward, and each move does one state update. With arrays over a small alphabet that is worst case; with hash maps, expected. A single shrink phase can be long, but the total cannot exceed : amortized per element.
"The longest run of 1s if you may flip at most zeros" is a window in disguise: flipping is never needed outside the window, so the rule is "at most zeros inside", which is hereditary. The contest version of the template in C++, for the longest window with sum over non-negative values:
#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 would let run past the end of the array.
The bits are and you may flip at most 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 , 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 to , where stretches are too many but one pass fits.
| Problem (in brief) | Window state and rule | Cost |
|---|---|---|
| Longest substring without a repeated character | last-seen index; | |
| Shortest subarray with sum , positive values | running sum; shrink while the sum stays | |
| Longest subarray with at most distinct values | counts in a map; shrink while more than keys | expected |
| Smallest window of covering every character of | needed counts and a missing counter; shrink while covered | |
| Does contain a rearrangement of ? | fixed window of length ; letter counts and a match counter |
Find the length of the shortest subarray with sum at least , where values may be negative and . Which approach is correct and fast?
- The shortest-window template: shrink while the sum stays
- Sort the array, then use two pointers
- Prefix sums with a monotonic deque of candidate start positions
- 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 and , you want the largest with . A deque of starts with increasing values discards dominated starts and answers each in amortized: in all.
Key takeaways
- A fixed window updates its state with one entering and one leaving element: instead of , with counts and a match counter for anagram-style windows.
- The variable template grows every step and shrinks 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 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 " 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.
In the template for the shortest valid window, where must the answer be recorded?
- After the shrink loop ends
- Inside the shrink loop, before leaves
- Before enters
- Once, after the last
Show the answer
B. Inside the shrink loop, before leaves
The shrink loop runs while the window is valid and stops at the first invalid one. Each valid window must be measured before leaves; after the loop, the window is too short to be valid.
A single iteration of the outer loop may run the inner shrink loop times. Why is the whole scan still ?
- The inner loop runs at most once per outer iteration on average inputs
- only moves forward, so all the shrink loops together advance it at most times
- Hash maps make every iteration
- The window length is bounded by
Show the answer
B. only moves forward, so all the shrink loops together advance it at most times
Count moves instead of iterations: moves times and at most times, so there are at most moves in total, each followed by work. That is an amortized bound, valid for every input.
What is the length of the longest subsequence (not necessarily contiguous) of a string with no repeated character?
- The answer of the sliding window
longest_unique - It needs dynamic programming over prefixes
- The number of distinct characters in the string
- 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.
You must count the subarrays with exactly distinct values. Which approach is correct?
- One window that shrinks while it has more than distinct values, adding 1 whenever it has exactly
- Prefix sums of the values with a hash map
- Sort the array, then count runs
- Count the subarrays with at most distinct values, then subtract those with at most
Show the answer
D. Count the subarrays with at most distinct values, then subtract those with at most
"At most " is hereditary, so a window counts it in by adding for every . Subarrays with exactly distinct values are those with at most but not at most , and the second set is inside the first.
Go deeper
- Counting Subarrays with Windows · “At most k” minus “at most k − 1”, and when windows fail.
- Sliding-Window Aggregation · Windows for min, gcd and other operations you cannot subtract.
- Sliding Windows over Data Streams · Approximate counts in tiny memory: exponential histograms and DGIM.
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).