TechniqueTechniqueA reusable problem-solving pattern you apply on top of data structures to turn slow solutions into fast ones.e.g. Two pointers, sliding window, prefix sums
DSA Learning Studio · Chapter 05 · Array & String Techniques

Sliding Window — slide, don't recompute

Fixed-size and variable-size windows from first principles: the update identity, the two-pointer invariant, monotonic deques, counting tricks, and where the same idea runs inside TCP, rate limiters, stream processors and image filters — with five working labs.

Difficulty: Beginner → Intermediate (advanced section: Upper-intermediate) Reading time: ~90 minutes (+ 40 min exercises) Language: Python 3.8+

AChapter introduction

Prerequisites

You should be comfortable with Python lists, strings, for/while loops and dictionaries, and with reading Big-O statements such as "Θ(n) time, O(1) extra space". Chapter 01 (Time & Space Complexity) covers the notation and Chapter 02 (Arrays & Hashing) covers the dictionaries used as window state. Chapter 03 (Prefix Sum) is used in the sections on negative numbers. This chapter generalises the same-direction case of Chapter 04 (Two Pointers); reading it first helps but is not required.

Learning objectives

After completing this chapter you will be able to:

  1. Define a sliding window formally and tell fixed-size windows apart from variable-size (two-pointer) windows.
  2. Derive the O(1) update rule S′ = S − a[L] + a[R+1] and explain why it needs an invertible aggregate.
  3. Write the three variable-window templates — longest valid, shortest valid and count valid — and prove each runs in Θ(n) because both pointers only move forward.
  4. Maintain window maxima and minima with a monotonic deque and justify its amortized O(1) cost per element.
  5. Recognise when the technique fails (negative numbers with a sum condition, non-contiguous selections, non-monotone conditions) and choose prefix sums, heaps or other tools instead.
  6. Connect the pattern to production systems: TCP flow control, sliding-window rate limiting, windowed stream aggregation, SQL window frames and running max/min image filters.
The one-sentence promise Neighbouring windows overlap in all but one or two elements, so instead of recomputing each window from scratch you update the previous answer with what entered and what left — turning Θ(n·k) or Θ(n²) scans into Θ(n). [1][2]
How the visuals in this chapter are made This environment has no image-generation model, so every "whiteboard" illustration is drawn in code as SVG with marker-style strokes and handwriting labels. Positions, values and counts in every figure are computed from the real algorithm, so they are exact. All five interactive labs work: you can type your own input, play, pause, step forwards and backwards, and reset. Passages tagged Illustration are my own worked examples rather than claims taken from a source.

BFundamental understanding

What is a sliding window?

Many questions about arrays and strings ask about contiguous pieces: "the best 7-day stretch of sales", "the longest substring with no repeated letter", "the maximum in every 3-element block". A window is such a contiguous piece, described by two indices: a left end L and a right end R. The Competitive Programmer's Handbook defines a sliding window as "a constant-size subarray that moves from left to right through the array", for each position of which we compute some information [1][2]. The USACO Guide describes the variable-size form as a variation of the two pointers method in which both pointers move in the same direction to maintain a range of elements [3].

Formal definition Let a[0..n−1] be a sequence. A window is an index interval [L, R] with 0 ≤ L ≤ R < n, denoting the contiguous subsequence a[L], a[L+1], …, a[R] of length R − L + 1. A sliding-window algorithm visits a sequence of windows [L₀,R₀], [L₁,R₁], … in which both endpoints are non-decreasing (Lt+1 ≥ Lt, Rt+1 ≥ Rt), and maintains a summary state(L, R) that is updated incrementally when an element enters at the right or leaves at the left.
• Fixed-size window: R − L + 1 = k for every visited window, so each move adds one element and removes one [1].
• Variable-size window: the length changes; R advances to grow the window and L advances to shrink it, as long as both only move right [2][3].
In plain English Put a paper frame over a row of numbers. To look at the next group, you don't rewrite everything inside the frame — you slide it one place, cross off the number that fell out on the left, and add the one that appeared on the right.

Why the concept exists

The brute-force way to examine every window recomputes its summary from nothing. For fixed size k that costs about k operations per window and (n − k + 1)·k in total; for "find the best window of any length" there are n(n+1)/2 windows, so brute force is Θ(n²) windows, and Θ(n³) if each is re-summed. But consecutive windows share almost everything: [L, R] and [L+1, R+1] share k − 1 elements. A sliding window exploits that overlap. The Handbook presents the two-pointers method and the sliding-window minimum in its chapter on amortized analysis precisely because the work of a single step can vary while the total stays linear [1].

A short, verifiable history

"Sliding window" is a family name more than a single invention, and the idea appears in several fields:

  • Networking (1981 onward). TCP controls how much unacknowledged data may be in flight using a send window over the sequence-number space; the current specification, RFC 9293 (2022), which obsoletes the original RFC 793 from 1981, defines the send variables SND.UNA, SND.NXT and SND.WND and calls part of the sequence space "the send window" [13].
  • String matching (1987). Karp and Rabin's randomized pattern-matching algorithm computes a fingerprint of each length-m window of the text and updates it in constant time as the window moves — a rolling hash [8][6][5].
  • Image processing (1992). van Herk published a running max/min filter whose cost per pixel does not depend on the window size [19].
  • Data streams (2002). Datar, Gionis, Indyk and Motwani formalised the sliding window model of streaming — answer queries about only the last N items — and showed how to approximate counts and sums in small memory [17][18].
  • Algorithm education and competitive programming. The fixed window, the two-pointer variable window and the deque-based window minimum are standard material in the Competitive Programmer's Handbook, the USACO Guide and CP-Algorithms [1][2][4].

Fundamental principles (introduced one term at a time)

TermMeaningExample on a = [2, 1, 5, 1, 3, 2]
Window [L, R]Contiguous index range, inclusive on both ends[1, 3] → elements 1, 5, 1
Window lengthR − L + 1 (not R − L)3 − 1 + 1 = 3
ExpandMove R right by one; an element enters[1,3] → [1,4], 3 enters
ShrinkMove L right by one; an element leaves[1,4] → [2,4], 1 leaves
SlideExpand and shrink together (fixed size)[1,3] → [2,4]
Window stateThe summary kept up to date: a sum, a count map, a deque…sum of [1,3] = 7
Valid / invalidWhether the window satisfies the problem's condition"sum ≥ 7": [1,3] is valid
Monotone conditionShrinking a valid window keeps it valid (or growing an invalid one keeps it invalid)"at most K distinct" — removing items never adds distinct values

Three principles carry the whole chapter. (1) Reuse: derive state(L′, R′) from state(L, R) rather than from scratch. (2) Monotone pointers: neither pointer moves backward, so the number of moves is at most 2n — this is the amortized argument behind the two-pointers method [1]. (3) Cheap updates: entering and leaving must each cost O(1), at least on average. That is easy for sums, and needs a cleverer structure — a monotonic deque or two stacks — for minima and maxima, which cannot be "subtracted" [4].

CThe problem statement

Problem description

We study two canonical problems, one of each kind.

Problem 1 · fixed window Input: an integer array a of length n and an integer k, 1 ≤ k ≤ n.
Output: the largest sum of any k consecutive elements.
Example: a = [2,1,5,1,3,2], k = 3 → 9 (window [5,1,3]).
Typical constraints: n ≤ 10⁵ … 10⁶, values may be negative.
Problem 2 · variable window Input: a string s of length n.
Output: the length of the longest substring with no repeated character.
Example: "abcabcbb" → 3 ("abc"); "pwwkew" → 3 ("wke").
Typical constraints: n ≤ 5·10⁴, any characters. This is LeetCode 3 [22].

Why the naive approach is inefficient

For Problem 1, summing each of the n − k + 1 windows separately costs (n − k + 1)·k additions. With n = 10⁶ and k = 10³ that is about 10⁹ — seconds to minutes in Python — while the sliding version needs about k + 2(n − k) ≈ 2·10⁶ operations (Figure D.4). For Problem 2, checking every substring for uniqueness examines Θ(n²) substrings at Θ(n) each, Θ(n³) total; even the smarter "extend each start until a repeat" is Θ(n²) in the worst case. The sliding window solves both in Θ(n) [1][2].

Limitations of alternative approaches

  • Prefix sums answer any range-sum query in O(1) after O(n) preprocessing, so they solve Problem 1 too — but they need O(n) extra memory and only work for invertible aggregates like sums. They cannot give a window's maximum, its number of distinct letters or "is it an anagram?" by subtraction (see Chapter 03).
  • A heap can keep a window maximum in O(log k) per step, so O(n log k) overall, and needs "lazy deletion" because heaps cannot remove arbitrary elements cheaply. A monotonic deque does the same job in amortized O(1) per step [4][2].
  • Segment trees and sparse tables answer arbitrary range queries, which is more than we need when the queried ranges move in one direction.

How the sliding window improves the solution

Both problems have the same hidden structure: the windows we care about can be visited in an order in which both endpoints only move right, and the summary can be updated in O(1) when one element enters or leaves. Under those two conditions the total work is proportional to the number of pointer moves, which is at most 2n [1].

Real-world analogy: the train window Illustration You are on a train counting houses visible through your window. When the train moves forward by one house, you don't recount the whole view — one house disappeared at the back edge and one appeared at the front. Keep a running tally, subtract the one that left, add the one that arrived. A variable window is like a caterpillar crawling along a branch: its head (R) reaches forward; when it is stretched too far (the window became invalid) its tail (L) catches up; neither end ever crawls backwards.

DVisual whiteboard explanations

Colour code used everywhere in this chapter: blue = data, green = current window / results, red = leaving, invalid or errors, yellow/orange = the active element or pointer, purple = relationships (shared cells, invariants, deques).

Figure D.1 · Concept introductionNeighbouring windows overlap — brute force pays for the overlap again and again
array elementscells shared by neighbouring windowswasted re-workreused work
2 0 1 1 5 2 1 3 3 4 2 5 array a, n = 6 W0: 2+1+5 = 8 W1: 1+5+1 = 7 W2: 5+1+3 = 9 W3: 1+3+2 = 6 shared by W0 and W1 (k − 1 = 2 cells) brute force: 4 windows × 3 = 12 adds every window re-adds the shared cells sliding: 3 + 3 × 2 = 9 ops first window once, then −1 out, +1 in n = 10⁶, k = 10³: ≈10⁹ vs ≈2·10⁶
Step by step. (1) With k = 3 there are n − k + 1 = 4 windows W0…W3, drawn as coloured strokes under the array. (2) W0 and W1 share the two cells inside the dashed purple box — in general neighbours share k − 1 cells. (3) Brute force re-adds those shared cells for every window: 4 × 3 = 12 additions. (4) A sliding window builds W0 once (3 additions) and then does one subtraction and one addition per move. Technical interpretation: the cost drops from Θ((n − k + 1)·k) to Θ(n) because each element is added once and removed at most once [1].
Figure D.2 · Internal working (fixed window)One slide = one subtraction + one addition
window before the slideelement leaving (a[L])window after the slideshared, untouchedoutside the window
2 0 1 1 5 2 1 3 3 4 2 5 before: [1,5,1] sum S = 7 window L=1 … R=3 2 0 1 1 5 2 1 3 3 4 2 5 after: [5,1,3] sum S = 9 ① − a[L] = − 1 (leaves) ② + a[R+1] = + 3 (enters) shared — never re-read ③ S′ = S − a[L] + a[R+1] = 7 − 1 + 3 = 9 · O(1) work
Step by step. ① The element at the old left end, a[1] = 1, leaves: subtract it. ② The element just beyond the old right end, a[4] = 3, enters: add it. ③ The new sum follows from the old one with two operations, 7 − 1 + 3 = 9; the two shared cells (purple) are never read again. Technical interpretation: this works because addition has an inverse (subtraction). For an aggregate with no inverse — max, min, gcd — step ① is impossible and we need the deque of Section F/G [4].
Figure D.3 · Step-by-step execution (variable window)The caterpillar: grow on the right, shrink on the left
current window (valid: sum ≥ 7)already passed by L — never revisitednot yet reached by RR pointer
2 0 3 1 1 2 2 3 4 4 3 5 step 1 expand R until sum ≥ 7 L R [2,3,1,2] = 8 ✓ valid → record len 4 2 0 3 1 1 2 2 3 4 4 3 5 step 2 shrink L while still valid L R [1,2,4] = 7 ✓ → record len 3 2 0 3 1 1 2 2 3 4 4 3 5 step 3 expand, then shrink again L R [4,3] = 7 ✓ → best len 2 both L and R only move right → at most 2n pointer moves in total
Task: shortest subarray of [2,3,1,2,4,3] with sum ≥ 7 (LeetCode 209 [22]). Step by step. (1) R advances, adding 2, 3, 1, 2; at R = 3 the sum is 8 ≥ 7, so length 4 is recorded. (2) While the window stays valid, L advances and the length shrinks; each time the window is valid we record its length (4, then 3 for [1,2,4]). (3) Repeating expand-then-shrink ends with [4,3], length 2. Technical interpretation: because all numbers are positive, removing an element can only lower the sum, so once a window becomes invalid on the left it stays invalid for every larger L with the same R. That monotonicity is what lets L move only forward [1][3].
Figure D.4 · Time complexity visualizationOperations for n = 1,000,000 as the window grows
brute force (n − k + 1)·ksliding window k + 2(n − k)
10^6 10^7 10^8 10^9 10^10 1.0e7 2.0e6 k = 10 1.0e8 2.0e6 k = 100 1.0e9 2.0e6 k = 1,000 9.9e9 2.0e6 k = 10,000 operations (log scale) ■ brute force (n−k+1)·k ■ sliding k + 2(n−k) n = 1,000,000 elements
Reading the chart. The y-axis is logarithmic: each gridline is 10× the one below. Brute force grows in proportion to k (≈10⁷ at k = 10, ≈10¹⁰ at k = 10⁴), while the sliding window stays at about 2·10⁶ whatever k is. The numbers are exact operation counts from the two formulas, not timings. Technical interpretation: Θ(n·k) versus Θ(n); the sliding cost is independent of k.
Figure D.5 · Comparison with alternative approachesWhich tool fits? A decision flowchart
fixed windowhow to keep the statevariable windowuse prefix sums insteadnot a window problem
contiguous subarray / substring? not a window problem (subsequence → DP, sort…) no size k given? yes FIXED window add a[R], drop a[R−k] yes aggregate? sum/count/xor → 1 variable max/min → monotonic deque counts/anagram → hash map shrinking a valid window keeps it valid? (e.g. all positive, "at most K") no VARIABLE window (L, R →) longest: shrink while invalid shortest: shrink while valid count: += R − L + 1 yes prefix sums + hash map or deque over prefix sums (negatives) no
How to use it. (1) The answer must be a contiguous block; otherwise windows don't apply. (2) If the size is fixed, slide a size-k window and choose the state by aggregate: one running number for invertible aggregates; a monotonic deque for max/min [4]; a count map for "distinct" or anagram questions. (3) If the size is free, ask whether the validity condition is monotone. If yes, use the two-pointer variable window [3]. If no — typically sums with negative numbers — switch to prefix sums with a hash map or a deque over prefix sums (Section K).

EInteractive labs

Each lab precomputes every step of the real algorithm on your input, so Prev really goes back one step. Type your own data, then Play, Pause, Next, Prev or Reset. Invalid input is reported in red and nothing runs.

Lab 1Fixed window: running sum & best window
The first k elements are added one by one; after that every step subtracts the outgoing element (red) and adds the incoming one (orange). The counters compare the work done with brute force — try a larger k to watch the gap grow.
window sum–
best sum–
sliding ops0
brute-force ops0
Press Play or Next.
Lab 2Variable window: the two-pointer caterpillar
Pick a problem. The code panel highlights the line being executed; the state panel shows exactly what the algorithm stores.
L0
R–
best–
pointer moves0
Press Play or Next.
Lab 3Monotonic deque: maximum (or minimum) of every window
The deque stores indices whose values are strictly decreasing (for max) from front to back. Watch dominated values get popped from the back and expired indices leave from the front.
deque (front → back)
output
pushes0
pops (back + front)0
bound 2n–
Press Play or Next.
Lab 4Fixed window + frequency table: find every anagram
A window of length |p| slides over s. Two tables are compared: the letters p needs and the letters the window has. Green columns match; when every column matches, the window is an anagram (LeetCode 438).
columns matching–
anagrams found at[]
Press Play or Next.
Lab 5Pattern recognition drill
Interviews rarely say "use a sliding window". For each problem, pick the tool you would reach for first. Feedback explains the reasoning.
Score: 0 / 0

FInternal working

Memory representation: what the algorithm actually stores

A sliding window never copies the window. It stores the input once (which it reads but does not change), two integers L and R, and a window state sized to the question. Slicing a[L:R+1] inside the loop would silently bring the brute-force cost back, because a Python slice copies its elements, which is O(k) [11].

Figure F.1 · Memory representationInput + two pointers + one small state structure
input (read-only)current window a[L..R]pointer variableswindow state
4 0 2 1 7 2 1 3 8 4 3 5 5 6 input list (read-only, never copied or sliced) L = 2 R = 4 two integers: O(1) space window state — pick ONE kind sum = 16 O(1) — sums, counts, xor {7:1, 1:1, 8:1} O(min(k, Σ)) — hash map of counts deque [4] (index of 8) O(k) — monotonic deque of indices green = the current window a[L..R] = [7, 1, 8]
Step by step. (1) The list stays where it is; the window is just the index range between L and R. (2) The pointers are plain integers: O(1) space. (3) Exactly one kind of state is kept, chosen by the question: a running number (sum, count, xor) costs O(1); a frequency map costs O(min(k, Σ)), where Σ is the alphabet size; a monotonic deque costs O(k) in the worst case. Technical interpretation: auxiliary space is the size of the state, not the size of the window, unless the state is a copy of the window.

The three operations every window needs

  1. add(a[R]) — fold the entering element into the state (s += x, count[x] += 1, push onto the deque).
  2. remove(a[L]) — undo the leaving element (s -= x, count[x] -= 1 and delete the key at zero, pop the deque front if it has expired).
  3. query() — read the answer for the current window (s, len(count), a[dq[0]]).

Once these three are O(1), every window problem reduces to choosing when to call them.

Execution flow: the four templates

Template 1 · fixed size k
for R in range(n):
    add(a[R])                 # enters
    if R >= k:
        remove(a[R - k])      # leaves
    if R >= k - 1:
        record(query())       # window full
Template 2 · longest valid
L = 0
for R in range(n):
    add(a[R])
    while invalid():         # repair
        remove(a[L]); L += 1
    best = max(best, R - L + 1)
Template 3 · shortest valid
L = 0
for R in range(n):
    add(a[R])
    while valid():           # tighten
        best = min(best, R - L + 1)
        remove(a[L]); L += 1
Template 4 · count valid
L = total = 0
for R in range(n):
    add(a[R])
    while invalid():
        remove(a[L]); L += 1
    total += R - L + 1        # all starts L..R

The difference between Templates 2 and 3 is where the answer is recorded. For "longest" we repair the window until it is valid, then record. For "shortest" we record while the window is valid, shrinking it after each record. Template 4 relies on the same monotonicity: if [L, R] is the widest valid window ending at R, then every [L′, R] with L ≤ L′ ≤ R is valid too, giving R − L + 1 valid subarrays ending at R [1][3].

State changes, numbered: longest substring without repeats

For Problem 2 the state is a dictionary last_seen[ch] holding the most recent index of each character. When s[R] was already seen inside the window, L can jump straight past the earlier copy instead of shrinking one step at a time:

  1. Read ch = s[R].
  2. If ch in last_seen and last_seen[ch] ≥ L, the window would contain ch twice: set L = last_seen[ch] + 1.
  3. Record last_seen[ch] = R.
  4. The window [L, R] now has no repeats: update best = max(best, R − L + 1).
Figure F.2 · Step-by-step executionThe left pointer jumps past a repeat
s[R], just readearlier copy found via last_seenwindow after the jumpdictionary look-up
a 0 b 1 c 2 a 3 b 4 c 5 b 6 b 7 R = 3, reads "a" last_seen["a"] = 0 ≥ L L jumps 0 → 1 = last_seen + 1 window "bca" · len 3 a 0 b 1 c 2 a 3 b 4 c 5 b 6 b 7 R = 6, reads "b" last_seen["b"] = 4 ≥ L L jumps 3 → 5 = last_seen + 1 window "cb" · len 2
Step by step. At R = 3 the letter a was last seen at index 0, which is ≥ L = 0, so L jumps to 1 and the window becomes "bca". At R = 6 the letter b was last seen at 4 ≥ L = 3, so L jumps to 5 and the window is "cb". Technical interpretation: the check last_seen[ch] ≥ L matters. Without it, an occurrence that has already left the window could drag L backwards — for "abba" at R = 3, last_seen["a"] = 0 while L = 2 — which breaks the monotone-pointer guarantee.

The monotonic deque, internally

For window maxima the state is a double-ended queue of indices whose values are strictly decreasing from front to back. CP-Algorithms describes the min-version: keep only the elements that can still become the minimum, in non-decreasing order, and before pushing a new value pop every larger value from the back [4]. The USACO Guide uses a decreasing deque for the maximum and stores indices so it can tell when the front has left the window [2]. On each step R:

  1. Pop dominated from the back: while a[dq[-1]] ≤ a[R], pop. Those elements are older and not larger than a[R], so they can never again be the maximum of a window that contains R.
  2. Push R onto the back.
  3. Expire from the front: if dq[0] ≤ R − k, that index has left the window — pop it from the front.
  4. Query: once R ≥ k − 1, the window maximum is a[dq[0]].

Python's collections.deque supports appends and pops at either end in approximately O(1) time, whereas a list costs O(n) for pop(0) and insert(0, v) [9]. That is why a list is the wrong container here.

Edge cases that change the answer

CaseWhat goes wrongWhat to do
k > n or k ≤ 0No window exists; sum(a[:k]) silently sums fewer than k itemsValidate and raise ValueError (or return the problem's sentinel)
k == nExactly one window; the slide loop runs zero timesTemplate 1 already handles it
Empty inputVariable templates return 0; "shortest" must not return ∞Map ∞ → 0 or −1 as the specification says
Negative numbers with "sum ≥ target"Shrinking can increase the sum, so the window logic is wrongUse prefix sums + monotonic deque (LeetCode 862), Section K
Duplicates in the dequePopping with < instead of ≤ keeps equal values; still correct but the deque growsUse ≤ for max (or ≥ for min) on indices
Zero counts left in a dictlen(count) over-reports distinct valuesdel count[x] when it reaches 0
Floating-point averagesLong runs of += x; −= y accumulate rounding errorKeep an integer sum and divide at query time, or re-sum periodically

GMathematical foundation

G.1 The fixed-window update identity

Let S(i) = Σj=ii+k−1 a[j] be the sum of the window starting at i. Then

S(i+1) = Σj=i+1i+k a[j] = ( Σj=ii+k−1 a[j] ) − a[i] + a[i+k] = S(i) − a[i] + a[i+k].

Proof. The two sums share the terms a[i+1], …, a[i+k−1]; the first also has a[i] and the second also has a[i+k]. Adding and subtracting those single terms converts one into the other. ∎ The proof uses only associativity, commutativity and an inverse, so the identity holds for any abelian group operation — sum, xor, or multiplication over non-zero numbers. Max, min and gcd have no inverse, which is why they need a different structure [4].

G.2 Monotone validity: why L never has to move back

Call a condition P on windows shrink-closed if P([L, R]) implies P([L′, R′]) whenever L ≤ L′ ≤ R′ ≤ R: every sub-window of a valid window is valid. "At most K distinct values", "no repeated character" and "sum ≤ T with non-negative numbers" are shrink-closed. Define, for each R, the smallest valid left end L*(R) = min{ L : P([L, R]) }.

Lemma (monotone left end) If P is shrink-closed then L*(R) ≤ L*(R+1).

Proof. Let L′ = L*(R+1), so [L′, R+1] is valid. If L′ ≤ R, its sub-window [L′, R] is valid by shrink-closure, so L*(R) ≤ L′. If L′ = R+1, the inequality L*(R) ≤ R < L′ holds because the single-element window [R, R] is valid in these problems. ∎

Correctness of Template 2. Invariant: at the end of iteration R, L = L*(R). By the lemma, the correct left end for R+1 is never to the left of the current L, so starting from the current L and advancing while the window is invalid lands exactly on L*(R+1). Each window [L*(R), R] is the longest valid window ending at R, and the overall longest valid window ends at some R, so taking the maximum over R is correct. Template 4 counts, for each R, the valid windows [L′, R] with L*(R) ≤ L′ ≤ R; by shrink-closure that is all of them, R − L*(R) + 1.

For "shortest with sum ≥ target" (Template 3) the condition is grow-closed instead — every super-window of a valid window is valid when all numbers are positive — and the symmetric argument shows that the largest valid left end is also non-decreasing in R.

Figure G.1 · Proof intuitionAll windows as a grid — the valid left ends form a staircase
valid window [L, R]invalid windowL*(R), the pointer patharray values
L=0 L=1 L=2 L=3 L=4 L=5 L=6 R=0 1 R=1 2 R=2 1 R=3 3 R=4 3 R=5 4 R=6 1 nums = [1, 2, 1, 3, 3, 4, 1], K = 2 green: window has ≤ 2 distinct (valid) red: too many distinct (invalid) ● L(R) = smallest valid left end the purple path only goes right / down → L(R) never decreases each column: valid cells form one block ending at the diagonal → count = R − L + 1 L(R) = [0, 0, 0, 2, 2, 3, 5]
Step by step. Each cell is one window: column = R, row = L (only L ≤ R exists). (1) In every column the valid cells form one solid block that touches the diagonal — that is shrink-closure. (2) The top of each block is L*(R); joining these gives the purple path. (3) The path only moves right or down, never up: L never decreases. Technical interpretation: the algorithm walks this staircase instead of testing all n(n+1)/2 cells, and the path has at most 2n − 1 unit steps, so the work is Θ(n). The count of valid windows ending at R is the height of the green block, R − L*(R) + 1. All cells were computed from the data shown.

G.3 The 2n bound (aggregate amortized analysis)

In any two-pointer window, R takes the values 0, 1, …, n−1 once each, and L only increases and never exceeds n, so the inner while loop runs at most n times in total across the whole execution, even though a single iteration may shrink many times. The total number of add + remove calls is therefore at most n + n = 2n. This is the aggregate method of amortized analysis: bound the total cost of a sequence of operations, then divide [5][1].

G.4 The monotonic deque invariant

Invariant (maximum version) After processing index R, the deque holds indices i₁ < i₂ < … < im = R, all inside the window, with a[i₁] > a[i₂] > … > a[im], and a[i₁] = max a[R−k+1..R].

Why the front is the maximum. Suppose an index j in the window was removed from the back. It was removed when some later index j′ > j with a[j′] ≥ a[j] arrived. Because j′ > j, j′ stays in every window that still contains j, so j can never be the unique maximum: it is dominated. Every index that is not dominated is still in the deque, and the decreasing order makes the front the largest of them. Cost. Each index is pushed exactly once and popped at most once, from the back or the front, so the total number of deque operations is at most 2n, which is amortized O(1) per element and O(n) overall [4][1].

Figure G.2 · Before-and-after comparisonDomination: a newer, larger value retires older candidates
in the deque (candidates)newest elementpopped — dominated forever
window i=1..3: deque = [3, −1, −3] 3 i=1 -1 i=2 -3 i=3 values strictly decreasing front → back front (3) is the window maximum R=4 reads 5: pops −3, −1 (and old 3) -1 i=2 -3 i=3 5 i=4 5 is newer AND larger: −3, −1 (and 3) can never be a maximum again → popped forever
Step by step. Left: the window [3, −1, −3] (k = 3) keeps all three indices because their values decrease, and the front value 3 is the maximum. Right: 5 arrives. It is newer and larger than −3, −1 and 3, so all three are popped from the back; the deque becomes [4], and the maximum of [−1, −3, 5] is 5. Technical interpretation: this single step does three pops, but those elements are gone for good — that is the amortized argument.

G.5 Counting identities: "exactly K" from "at most K"

"Exactly K distinct" is not shrink-closed: removing an element can drop the count to K − 1. But "at most K" is, and

#{windows with exactly K distinct} = #{≤ K} − #{≤ K−1},

because the windows with at most K distinct values split into those with exactly K and those with at most K − 1. Each right-hand term is one run of Template 4, so the whole computation is Θ(n). On [1,2,1,2,3] with K = 2: atMost(2) = 12, atMost(1) = 5, difference 7 (verified in Section I). This is the standard solution to LeetCode 992 [22].

G.6 Rolling hashes (the same identity, modulo a prime)

Rabin–Karp treats a length-m window as a base-B number modulo a prime q: h(i) = (a[i]·Bm−1 + … + a[i+m−1]) mod q. Sliding by one gives

h(i+1) = ( (h(i) − a[i]·Bm−1)·B + a[i+m] ) mod q,

which is G.1 in a different group. The update is O(1), so all window hashes cost O(n + m), and equal hashes are confirmed by a direct comparison when needed [6][7][8].

HOperations and complexity analysis

Master table

Here n is the input length, k the window size, and Σ the number of distinct symbols. Hash-map costs are expected (average) costs.

Operation / algorithmBest caseAverage caseWorst caseAuxiliary space
Brute-force fixed windows (re-sum each)Θ(n·k)*Θ(n·k)Θ(n·k)O(1)
Fixed window, invertible aggregate (sum, count, xor)Θ(n)Θ(n)Θ(n)O(1)
Single slide step (sum)Θ(1)Θ(1)Θ(1)O(1)
Fixed window + frequency map (anagrams)Θ(n)Θ(n·Σ) with full-map compare; Θ(n) with a "matches" countersameO(Σ)
Variable window (two pointers), O(1) stateΘ(n)Θ(n)Θ(n)O(1)
Variable window with hash map stateΘ(n)Θ(n) expectedO(n²) only with adversarial hash collisionsO(min(n, Σ))
Single expand or shrink stepΘ(1)Θ(1) amortizedΘ(n) for one outer iteration (inner while), Θ(n) total—
Monotonic deque: all window max/minΘ(n)Θ(n)Θ(n)O(k)
Heap with lazy deletion: all window maxO(n log n)O(n log n)O(n log n)O(n)
Balanced BST / sorted container (median, k-th)Θ(n log k)Θ(n log k)Θ(n log k)O(k)
Rabin–Karp rolling hash (all windows)Θ(n + m)Θ(n + m) expectedΘ(n·m) if every hash collides and is verifiedO(1)

*Brute force always performs (n − k + 1)·k additions, so its best, average and worst cases coincide.

Reasoning behind each entry

  • Fixed window, Θ(n) in all cases. The first window costs k − 1 additions and each of the n − k slides costs one subtraction and one addition: exactly (k−1) + 2(n−k) arithmetic operations, between n−1 and 2n. It is O(n) because it is at most 2n, Ω(n) because every element must be read at least once, hence Θ(n).
  • Variable window, Θ(n). The 2n bound of G.3 gives O(n); reading every element gives Ω(n). One outer iteration can be Θ(n) on its own, which is the reason the bound is stated as amortized [1][5].
  • Monotonic deque, Θ(n). At most n pushes and n pops in total (G.4) [4].
  • Heap. Each push or pop costs O(log size), and with lazy deletion the heap can hold up to n entries, so O(n log n).

Theory versus actual Python behaviour

Python constructCostConsequence for window code
sum(a[L:R+1])O(k): the slice copies, then sum readsBrings back Θ(n·k); never do this per step [11]
list.pop(0), list.insert(0, x)O(n) memory movementUse collections.deque for queues [9]
deque.append/appendleft/pop/popleft≈O(1) at either endRight container for monotonic deques [9]
deque[i] in the middleO(n)Only peek at dq[0] and dq[-1] [9]
dict get / set / deleteO(1) average, O(n) amortized worst"Θ(n) expected" for count-map windows [11]
Counter == CounterO(number of keys)Fine for 26 letters; use a matches counter for big alphabets
numpy …sliding_window_view(x, k).sum(axis=1)Θ(n·k) arithmetic, but vectorisedThe view itself copies nothing, but NumPy's docs warn the approach can be much slower than a specialised algorithm for large windows [12]

Time–space trade-offs

A fixed-window sum uses O(1) space; prefix sums use O(n) space but answer arbitrary ranges, not just sliding ones. A monotonic deque uses up to O(k) memory to make max/min O(1) amortized; the alternative O(1)-space approach re-scans each window for Θ(n·k) time. In streaming systems where the window itself is too large to keep, exact answers can require memory proportional to the window, which motivates the approximate sketches in Section N [17].

IPython implementation

Everything below is one companion module, sliding_window.py, listed in full in I.13. Every function was executed and cross-checked against a brute-force reference on 3,000 random inputs; the output in I.8 is the real output of that run.

I.1 Fixed window: maximum sum of k consecutive elements

def _check_k(n: int, k: int) -> None:
    if not isinstance(k, int) or isinstance(k, bool):
        raise TypeError("k must be an int")
    if k <= 0:
        raise ValueError("k must be positive")
    if k > n:
        raise ValueError(f"k={k} is larger than the input length n={n}")
def max_sum_fixed(nums: Sequence[int], k: int) -> int:
    """Largest sum of any k consecutive elements.  Theta(n) time, O(1) space."""
    _check_k(len(nums), k)
    window = sum(nums[:k])            # build the first window: k additions
    best = window
    for right in range(k, len(nums)): # slide: one element in, one element out
        window += nums[right] - nums[right - k]
        best = max(best, window)
    return best
LineWhy it is there
_check_k(len(nums), k)Rejects k ≤ 0, k > n and non-integers. Without it, nums[:k] with k > n would quietly sum fewer than k elements.
window = sum(nums[:k])Builds the first window once. This is the only slice, executed once: O(k).
for right in range(k, len(nums))right is the index entering the window; the leaving index is right − k.
window += nums[right] - nums[right - k]The identity S′ = S − a[L] + a[R+1] from G.1, as one statement.
best = max(best, window)Each window is examined exactly once, in left-to-right order.

I.2 Template 1 in its general form: moving averages

Writing the loop over every index — add, then remove once the window is over-full, then record once it is full — is easier to adapt than the "build first, then slide" version above. It is the same algorithm.

def window_averages(nums: Sequence[float], k: int) -> List[float]:
    """Average of every length-k window (a moving average)."""
    _check_k(len(nums), k)
    out, window = [], 0.0
    for right, x in enumerate(nums):
        window += x                    # element enters on the right
        if right >= k:
            window -= nums[right - k]  # element leaves on the left
        if right >= k - 1:             # window is full -> record it
            out.append(window / k)
    return out

I.3 Variable window, longest: no repeated characters

def longest_unique_substring(s: str) -> int:
    """Length of the longest substring with no repeated character."""
    last_seen = {}          # char -> most recent index
    left = best = 0
    for right, ch in enumerate(s):
        if ch in last_seen and last_seen[ch] >= left:
            left = last_seen[ch] + 1      # jump past the earlier copy
        last_seen[ch] = right
        best = max(best, right - left + 1)
    return best

The jump left = last_seen[ch] + 1 replaces a while loop that would remove characters one by one. Both are Θ(n), but the jump does fewer dictionary operations. The guard last_seen[ch] >= left is essential (Figure F.2).

I.4 Variable window, shortest: sum at least target

def min_len_subarray_at_least(target: int, nums: Sequence[int]) -> int:
    """Shortest subarray with sum >= target (all nums must be positive).
    Returns 0 when no such subarray exists (LeetCode 209 convention)."""
    if any(x <= 0 for x in nums):
        raise ValueError("this sliding window requires strictly positive numbers")
    left = window = 0
    best = float("inf")
    for right, x in enumerate(nums):
        window += x                          # expand
        while window >= target:              # valid -> shrink while still valid
            best = min(best, right - left + 1)
            window -= nums[left]
            left += 1
    return 0 if best == float("inf") else best

The positivity check is error handling for a correctness precondition: with a zero or negative element the shrink logic of G.2 no longer holds, so the function refuses rather than return a wrong answer. For negative inputs, see the deque-over-prefix-sums solution in Section M.

I.5 Variable window, count: at most K distinct, and exactly K

def longest_at_most_k_distinct(nums: Sequence, k: int) -> int:
    """Longest window containing at most k distinct values."""
    if k < 0:
        raise ValueError("k must be non-negative")
    count = Counter()
    left = best = 0
    for right, x in enumerate(nums):
        count[x] += 1
        while len(count) > k:                # invalid -> shrink until valid
            count[nums[left]] -= 1
            if count[nums[left]] == 0:
                del count[nums[left]]
            left += 1
        best = max(best, right - left + 1)
    return best
def count_at_most_k_distinct(nums: Sequence, k: int) -> int:
    """Number of subarrays with at most k distinct values."""
    if k < 0:
        return 0
    count = Counter()
    left = total = 0
    for right, x in enumerate(nums):
        count[x] += 1
        while len(count) > k:
            count[nums[left]] -= 1
            if count[nums[left]] == 0:
                del count[nums[left]]
            left += 1
        total += right - left + 1            # every start in [left, right] works
    return total
def count_exactly_k_distinct(nums: Sequence, k: int) -> int:
    """exactly(k) = atMost(k) - atMost(k-1)."""
    return count_at_most_k_distinct(nums, k) - count_at_most_k_distinct(nums, k - 1)

I.6 Monotonic deque: maximum of every window

def sliding_window_max(nums: Sequence[int], k: int) -> List[int]:
    """Maximum of every length-k window.  Theta(n) time, O(k) extra space."""
    _check_k(len(nums), k)
    dq = deque()            # indices; their values are strictly decreasing
    out = []
    for right, x in enumerate(nums):
        while dq and nums[dq[-1]] <= x:      # x dominates smaller/equal values
            dq.pop()
        dq.append(right)
        if dq[0] <= right - k:               # front index has left the window
            dq.popleft()
        if right >= k - 1:
            out.append(nums[dq[0]])
    return out
LineWhy it is there
dq = deque()Holds indices, so the front's position can be checked against the window's left edge [2].
while dq and nums[dq[-1]] <= x: dq.pop()Removes dominated candidates (G.4). Using <= also removes equal older values, which keeps the deque strictly decreasing.
if dq[0] <= right - k: dq.popleft()At most one index can expire per step, because exactly one index (right − k) leaves per slide.
out.append(nums[dq[0]])The front is the maximum by the invariant.

I.7 Fixed window with a frequency table: anagram positions

def find_anagrams(s: str, p: str) -> List[int]:
    """Start indices of every substring of s that is a permutation of p."""
    k = len(p)
    if k == 0 or k > len(s):
        return []
    need = Counter(p)
    have = Counter()
    out = []
    for right, ch in enumerate(s):
        have[ch] += 1
        if right >= k:                       # drop the outgoing character
            left_ch = s[right - k]
            have[left_ch] -= 1
            if have[left_ch] == 0:
                del have[left_ch]            # keep the Counter comparable
        if have == need:                     # O(alphabet) comparison
            out.append(right - k + 1)
    return out

del have[left_ch] keeps the two Counters comparable with ==. Comparing two Counters costs O(number of keys), bounded by the alphabet size. For huge alphabets, keep an integer matches that counts letters whose needed and current counts agree, and update it in O(1) per step.

I.8 Sample run — actual output

$ python3 sliding_window.py
max_sum_fixed([2, 1, 5, 1, 3, 2], 3)        -> 9
window_averages([1, 3, 2, 6, -1, 4], 3)     -> [2.0, 3.67, 2.33, 3.0]
find_anagrams('cbaebabacd', 'abc')          -> [0, 6]
longest_unique_substring('abcabcbb')        -> 3
longest_unique_substring('pwwkew')          -> 3
min_len_subarray_at_least(7, [2,3,1,2,4,3]) -> 2
longest_at_most_k_distinct('eceba', 2)      -> 3
count_exactly_k_distinct([1,2,1,2,3], 2)    -> 7
sliding_window_max([1,3,-1,-3,5,3,6,7], 3)  -> [3, 3, 5, 5, 6, 7]
list(sliding_window('ABCDE', 3))            -> ['ABC', 'BCD', 'CDE']
error handled: ValueError - k=3 is larger than the input length n=2
error handled: ValueError - k must be positive
error handled: ValueError - this sliding window requires strictly positive numbers
self-test passed: 3000 random cases x 9 functions

I.9 Dry-run tables

(a) max_sum_fixed([2, 1, 5, 1, 3, 2], k=3)

rightentersleaveswindowwindow sumbest
init2, 1, 5—[2, 1, 5]88
312[1, 5, 1]8 − 2 + 1 = 78
431[5, 1, 3]7 − 1 + 3 = 99
525[1, 3, 2]9 − 5 + 2 = 69

(b) longest_unique_substring("abcabcbb")

Rchlast_seen[ch] beforeL before → afterwindowlengthbest
0a—0 → 0a11
1b—0 → 0ab22
2c—0 → 0abc33
3a0 (≥ L)0 → 1bca33
4b1 (≥ L)1 → 2cab33
5c2 (≥ L)2 → 3abc33
6b4 (≥ L)3 → 5cb23
7b6 (≥ L)5 → 7b13

(c) min_len_subarray_at_least(7, [2, 3, 1, 2, 4, 3])

Raddsum after addshrink steps (record length, then remove a[L])L aftersum afterbest
022— (2 < 7)02∞
135—05∞
216—06∞
328[0,3] len 4 → remove 2164
4410[1,4] len 4 → remove 3; [2,4] len 3 → remove 1363
539[3,5] len 3 → remove 2; [4,5] len 2 → remove 4532

(d) sliding_window_max([1, 3, -1, -3, 5, 3, 6, 7], k=3)

Ra[R]popped from backexpired from frontdeque (indices)deque (values)output
01——[0][1]—
130—[1][3]—
2−1——[1, 2][3, −1]3
3−3——[1, 2, 3][3, −1, −3]3
453, 2, 1—[4][5]5
53——[4, 5][5, 3]5
665, 4—[6][6]6
776—[7][7]7

In this classic input the front never expires, because every old maximum is overtaken from the back first. Dry-run exercise 3 in Section P uses an input where it does.

I.10 Edge cases and error handling

CallResultReason
max_sum_fixed([1, 2], 3)ValueError: k=3 is larger than the input length n=2No window of size 3 exists
max_sum_fixed([1, 2], 0)ValueError: k must be positiveA size-0 window has no defined maximum sum
max_sum_fixed([-5, -2, -9], 2)−7Negative numbers are fine for fixed windows: no shrink decision is made
min_len_subarray_at_least(3, [1, -1, 4])ValueError (positivity)Precondition of the variable window violated
min_len_subarray_at_least(100, [1, 2])0No valid window: the LeetCode 209 convention
longest_unique_substring("")0Loop body never runs
longest_at_most_k_distinct([1, 2], 0)0Every non-empty window is invalid, so L overtakes R and the length is R − L + 1 = 0
find_anagrams("ab", "abc")[]Pattern longer than text

I.11 Built-in Python alternatives

  • collections.deque(maxlen=k) keeps the last k items automatically: when a bounded deque is full, appending discards an item from the opposite end [9]. It is ideal for "last k events" buffers.
  • itertools recipe sliding_window(iterable, n) yields overlapping fixed-length tuples using exactly that bounded deque: sliding_window('ABCDEFG', 3) → ABC BCD CDE DEF EFG [10]. Building each tuple costs O(k), so use it to see windows, not to aggregate big ones.
  • itertools.pairwise (Python 3.10+) is the k = 2 special case: successive overlapping pairs [10].
  • numpy.lib.stride_tricks.sliding_window_view (NumPy 1.20+) returns a read-only view of every window without copying data [12]. Reductions over it are vectorised but still Θ(n·k); the documentation notes this generic approach can be far slower than a specialised algorithm for large windows [12].
def sliding_window(iterable: Iterable, k: int) -> Iterator[tuple]:
    """Lazy windows over any iterable (same idea as the itertools recipe)."""
    if k <= 0:
        raise ValueError("k must be positive")
    it = iter(iterable)
    win = deque(maxlen=k)
    for x in it:
        win.append(x)        # maxlen evicts the oldest item automatically
        if len(win) == k:
            yield tuple(win)

I.12 Comparison of implementations

Approach (fixed-window sums)TimeExtra spaceWorks for max/min?Streams (unknown n)?
Re-sum every window sum(a[i:i+k])Θ(n·k)O(k) per sliceYes (max instead of sum)No (needs indexing)
Running sum (I.1, I.2)Θ(n)O(1)No — max has no inverseYes, if the last k items are buffered
Prefix sums P[i+k] − P[i]Θ(n)O(n)NoPartly
Monotonic deque (I.6)Θ(n)O(k)YesYes
sliding_window recipe + sumΘ(n·k)O(k)YesYes
NumPy sliding_window_view(...).sum(1)Θ(n·k), vectorisedO(n) outputYesNo

I.13 The complete, runnable module

Show sliding_window.py (all functions + self-test)
"""sliding_window.py — companion module for the Sliding Window chapter.

Every function is written from scratch, validated, and cross-checked
against a brute-force reference in ``_self_test()``.
"""
from collections import Counter, deque
from typing import Iterable, Iterator, List, Sequence


# ---------------------------------------------------------------- fixed size
def _check_k(n: int, k: int) -> None:
    if not isinstance(k, int) or isinstance(k, bool):
        raise TypeError("k must be an int")
    if k <= 0:
        raise ValueError("k must be positive")
    if k > n:
        raise ValueError(f"k={k} is larger than the input length n={n}")


def max_sum_fixed(nums: Sequence[int], k: int) -> int:
    """Largest sum of any k consecutive elements.  Theta(n) time, O(1) space."""
    _check_k(len(nums), k)
    window = sum(nums[:k])            # build the first window: k additions
    best = window
    for right in range(k, len(nums)): # slide: one element in, one element out
        window += nums[right] - nums[right - k]
        best = max(best, window)
    return best


def window_averages(nums: Sequence[float], k: int) -> List[float]:
    """Average of every length-k window (a moving average)."""
    _check_k(len(nums), k)
    out, window = [], 0.0
    for right, x in enumerate(nums):
        window += x                    # element enters on the right
        if right >= k:
            window -= nums[right - k]  # element leaves on the left
        if right >= k - 1:             # window is full -> record it
            out.append(window / k)
    return out


def find_anagrams(s: str, p: str) -> List[int]:
    """Start indices of every substring of s that is a permutation of p."""
    k = len(p)
    if k == 0 or k > len(s):
        return []
    need = Counter(p)
    have = Counter()
    out = []
    for right, ch in enumerate(s):
        have[ch] += 1
        if right >= k:                       # drop the outgoing character
            left_ch = s[right - k]
            have[left_ch] -= 1
            if have[left_ch] == 0:
                del have[left_ch]            # keep the Counter comparable
        if have == need:                     # O(alphabet) comparison
            out.append(right - k + 1)
    return out


# ------------------------------------------------------------- variable size
def longest_unique_substring(s: str) -> int:
    """Length of the longest substring with no repeated character."""
    last_seen = {}          # char -> most recent index
    left = best = 0
    for right, ch in enumerate(s):
        if ch in last_seen and last_seen[ch] >= left:
            left = last_seen[ch] + 1      # jump past the earlier copy
        last_seen[ch] = right
        best = max(best, right - left + 1)
    return best


def min_len_subarray_at_least(target: int, nums: Sequence[int]) -> int:
    """Shortest subarray with sum >= target (all nums must be positive).
    Returns 0 when no such subarray exists (LeetCode 209 convention)."""
    if any(x <= 0 for x in nums):
        raise ValueError("this sliding window requires strictly positive numbers")
    left = window = 0
    best = float("inf")
    for right, x in enumerate(nums):
        window += x                          # expand
        while window >= target:              # valid -> shrink while still valid
            best = min(best, right - left + 1)
            window -= nums[left]
            left += 1
    return 0 if best == float("inf") else best


def longest_at_most_k_distinct(nums: Sequence, k: int) -> int:
    """Longest window containing at most k distinct values."""
    if k < 0:
        raise ValueError("k must be non-negative")
    count = Counter()
    left = best = 0
    for right, x in enumerate(nums):
        count[x] += 1
        while len(count) > k:                # invalid -> shrink until valid
            count[nums[left]] -= 1
            if count[nums[left]] == 0:
                del count[nums[left]]
            left += 1
        best = max(best, right - left + 1)
    return best


def count_at_most_k_distinct(nums: Sequence, k: int) -> int:
    """Number of subarrays with at most k distinct values."""
    if k < 0:
        return 0
    count = Counter()
    left = total = 0
    for right, x in enumerate(nums):
        count[x] += 1
        while len(count) > k:
            count[nums[left]] -= 1
            if count[nums[left]] == 0:
                del count[nums[left]]
            left += 1
        total += right - left + 1            # every start in [left, right] works
    return total


def count_exactly_k_distinct(nums: Sequence, k: int) -> int:
    """exactly(k) = atMost(k) - atMost(k-1)."""
    return count_at_most_k_distinct(nums, k) - count_at_most_k_distinct(nums, k - 1)


# --------------------------------------------------------- monotonic deque
def sliding_window_max(nums: Sequence[int], k: int) -> List[int]:
    """Maximum of every length-k window.  Theta(n) time, O(k) extra space."""
    _check_k(len(nums), k)
    dq = deque()            # indices; their values are strictly decreasing
    out = []
    for right, x in enumerate(nums):
        while dq and nums[dq[-1]] <= x:      # x dominates smaller/equal values
            dq.pop()
        dq.append(right)
        if dq[0] <= right - k:               # front index has left the window
            dq.popleft()
        if right >= k - 1:
            out.append(nums[dq[0]])
    return out


def sliding_window(iterable: Iterable, k: int) -> Iterator[tuple]:
    """Lazy windows over any iterable (same idea as the itertools recipe)."""
    if k <= 0:
        raise ValueError("k must be positive")
    it = iter(iterable)
    win = deque(maxlen=k)
    for x in it:
        win.append(x)        # maxlen evicts the oldest item automatically
        if len(win) == k:
            yield tuple(win)


# ------------------------------------------------------------- self test
def _self_test(trials: int = 3000) -> None:
    import random
    rnd = random.Random(2026)
    for _ in range(trials):
        n = rnd.randint(1, 14)
        a = [rnd.randint(-9, 9) for _ in range(n)]
        k = rnd.randint(1, n)
        assert max_sum_fixed(a, k) == max(sum(a[i:i + k]) for i in range(n - k + 1))
        assert sliding_window_max(a, k) == [max(a[i:i + k]) for i in range(n - k + 1)]
        assert [round(v, 9) for v in window_averages(a, k)] == \
               [round(sum(a[i:i + k]) / k, 9) for i in range(n - k + 1)]
        assert list(sliding_window(a, k)) == [tuple(a[i:i + k]) for i in range(n - k + 1)]
        pos = [abs(x) + 1 for x in a]
        t = rnd.randint(1, 40)
        brute = min((j - i + 1 for i in range(n) for j in range(i, n)
                     if sum(pos[i:j + 1]) >= t), default=0)
        assert min_len_subarray_at_least(t, pos) == brute
        s = "".join(rnd.choice("abcd") for _ in range(n))
        assert longest_unique_substring(s) == max(
            (j - i for i in range(n + 1) for j in range(i, n + 1)
             if len(set(s[i:j])) == j - i), default=0)
        small = [rnd.randint(1, 4) for _ in range(n)]
        kk = rnd.randint(0, 4)
        subs = [small[i:j + 1] for i in range(n) for j in range(i, n)]
        assert count_exactly_k_distinct(small, kk) == sum(len(set(x)) == kk for x in subs)
        assert longest_at_most_k_distinct(small, kk) == max(
            [len(x) for x in subs if len(set(x)) <= kk], default=0)
        p = "".join(rnd.choice("ab") for _ in range(rnd.randint(1, 3)))
        assert find_anagrams(s, p) == [i for i in range(n - len(p) + 1)
                                       if sorted(s[i:i + len(p)]) == sorted(p)]
    print(f"self-test passed: {trials} random cases x 9 functions")


if __name__ == "__main__":
    print("max_sum_fixed([2, 1, 5, 1, 3, 2], 3)        ->", max_sum_fixed([2, 1, 5, 1, 3, 2], 3))
    print("window_averages([1, 3, 2, 6, -1, 4], 3)     ->",
          [round(v, 2) for v in window_averages([1, 3, 2, 6, -1, 4], 3)])
    print("find_anagrams('cbaebabacd', 'abc')          ->", find_anagrams("cbaebabacd", "abc"))
    print("longest_unique_substring('abcabcbb')        ->", longest_unique_substring("abcabcbb"))
    print("longest_unique_substring('pwwkew')          ->", longest_unique_substring("pwwkew"))
    print("min_len_subarray_at_least(7, [2,3,1,2,4,3]) ->", min_len_subarray_at_least(7, [2, 3, 1, 2, 4, 3]))
    print("longest_at_most_k_distinct('eceba', 2)      ->", longest_at_most_k_distinct("eceba", 2))
    print("count_exactly_k_distinct([1,2,1,2,3], 2)    ->", count_exactly_k_distinct([1, 2, 1, 2, 3], 2))
    print("sliding_window_max([1,3,-1,-3,5,3,6,7], 3)  ->", sliding_window_max([1, 3, -1, -3, 5, 3, 6, 7], 3))
    print("list(sliding_window('ABCDE', 3))            ->", ["".join(w) for w in sliding_window("ABCDE", 3)])
    for bad in [lambda: max_sum_fixed([1, 2], 3), lambda: max_sum_fixed([1, 2], 0),
                lambda: min_len_subarray_at_least(3, [1, -1, 4])]:
        try:
            bad()
        except (ValueError, TypeError) as e:
            print("error handled:", type(e).__name__, "-", e)
    _self_test()

JReal-world applications

Only applications where a window over a sequence is the actual mechanism are listed here. Each entry says which part of the chapter it uses.

J.1 Networking: TCP flow control

TCP numbers every byte. The receiver advertises in each segment a window: the number of data octets, starting from the acknowledged one, that it is willing to accept [13]. The sender keeps SND.UNA (oldest unacknowledged), SND.NXT (next to send) and SND.WND (send window), and RFC 9293's Figure 3 splits the sequence space into four regions, region 3 being the send window [13]. As acknowledgements arrive, SND.UNA moves right and the window slides along the byte stream — a variable-size window whose left end only advances.

Figure J.1 · Real-world applicationThe TCP send window over the sequence-number space
1 · acknowledged2 · in flight3 · usable now4 · not yet allowedwindow bounds
SND.UNA SND.NXT SND.UNA + SND.WND 1 · sent & ACKed 2 · sent, not ACKed 3 · may send now 4 · not yet allowed send window (regions 2 + 3) slides right as ACKs arrive sequence numbers → (each box = a chunk of bytes; illustration)
Step by step. (1) Bytes before SND.UNA are acknowledged and can be forgotten (left end of the window). (2) Bytes between SND.UNA and SND.NXT were sent and await ACKs. (3) Bytes up to SND.UNA + SND.WND may be sent immediately. (4) Anything beyond must wait. An ACK moves SND.UNA right, so the window slides. Technical interpretation: region layout and variable names follow RFC 9293 §3.3.1 [13]; the box sizes are illustrative.

J.2 Backend engineering: sliding-window rate limiting

Cloudflare described a rate limiter that approximates "requests in the last 60 seconds" with only two counters per key: the previous minute's count, weighted by how much of it still overlaps the sliding window, plus the current minute's count. Their worked example, with a limit of 50 requests per minute, 42 requests in the previous minute and 18 in the 15 seconds of the current one, estimates 42 × (45/60) + 18 = 49.5 [14]. Measured on 400 million requests from 270,000 sources, 0.003% of requests were wrongly allowed or rate-limited, and the approach needed far less memory than storing a timestamp per request [14].

Figure J.2 · Real-world applicationA two-counter estimate of a sliding 60-second window
previous fixed minuteelapsed part of the current minutesliding window ending nowoverlap fraction
previous minute: 42 requests 18 req sliding 60-second window ending "now" 45 s of the previous minute = 75 % now = 15 s into this minute rate ≈ 42 × (45/60) + 18 = 31.5 + 18 = 49.5 limit 50/min → allowed, but the next request would exceed it memory per key: two counters instead of one timestamp per request
Step by step. (1) Keep fixed-minute counters. (2) The 60-second window ending "now" covers the last 45 s of the previous minute (75%) and the first 15 s of this one. (3) Assume the previous minute's requests were evenly spread, so 75% of its 42 still count. (4) Compare the estimate 49.5 with the limit 50. Technical interpretation: this trades exactness (a timestamp log — an exact variable window) for O(1) memory per key — the same trade-off as in Section H. Numbers are those of the cited example [14].

J.3 Distributed systems and stream processing: windowed aggregation

Apache Flink assigns stream elements to windows. Tumbling windows have a fixed size and do not overlap; sliding windows have a size and a slide interval, overlap when the slide is smaller than the size, and then assign each element to several windows [15]. A "5-minute average every minute" is exactly a fixed window advanced in steps, and incremental (add/remove) aggregation is how such systems avoid recomputing each window. In the theory of data streams, the sliding-window model keeps only the last N elements relevant [23][17].

J.4 Databases: SQL window frames

PostgreSQL's window functions accept a frame clause such as ROWS BETWEEN 2 PRECEDING AND CURRENT ROW. The frame is the set of rows, a subset of the partition, that the function acts on, and it moves with the current row [16]. A 3-row moving average is therefore a fixed-size sliding window written declaratively:

SELECT day, revenue,
       AVG(revenue) OVER (ORDER BY day
                          ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) AS avg_3d
FROM daily_sales;

The documentation also notes that frames near the partition edges contain fewer rows [16] — the SQL equivalent of the "window not yet full" check in Template 1.

J.5 Search, security and storage: rolling hashes over text

Substring search sits at network choke points and in spam and forensics tools; Princeton's algorithms course lists such applications for substring search and presents Rabin–Karp as its rolling-fingerprint method [7][6]. Each length-m window of the text is hashed in O(1) from the previous one (G.6), so all candidate positions cost O(n) hash updates [8][5]. The same exercise list shows how to extend it to searching for several equal-length patterns at once by storing their hashes in a set [6].

J.6 Image and signal processing: running max/min filters

Morphological dilation and erosion take the maximum or minimum over a sliding neighbourhood. MATLAB's imdilate and imerode use van Herk's algorithm, so the time for a flat rectangular structuring element does not depend on its size [21][19]. The 1-D core is exactly "maximum of every window", solved without a deque by block-wise prefix and suffix maxima (Section N) [20].

J.7 Operating systems and monitoring

Illustration Dashboards that show "error rate over the last 5 minutes" or "p99 latency over the last 1,000 requests" maintain fixed windows over event streams; a deque(maxlen=1000) or a ring buffer plus running counters is the in-process version of Template 1. This is a design pattern rather than a claim about any specific product.

KComparison with alternatives

K.1 Tools for contiguous-range problems

TechniqueBest atTimeSpaceBreaks when…
Fixed sliding windowEvery window of one size k, aggregates with O(1) add/removeΘ(n)O(1)–O(k)Windows of many different sizes are queried
Variable sliding windowLongest / shortest / count of windows under a monotone conditionΘ(n)O(1)–O(Σ)The condition is not monotone (e.g. negative numbers with a sum target)
Two pointers from both endsPairs in a sorted array (two-sum, container with most water)Θ(n)O(1)Input is unsorted and order matters [3]
Prefix sumsArbitrary range sums; "sum exactly K" counts with a hash map; works with negativesΘ(n)O(n)Aggregate is not invertible (max, distinct)
Monotonic dequeSliding max/min; deque-optimised DPΘ(n)O(k)Queries are arbitrary ranges [4]
Heap / sorted containerSliding median, k-th largestO(n log k)O(k)— (slower but general)
Sparse table / segment treeMany arbitrary range-min/max/sum queriesO(n log n) build, O(1)–O(log n) queryO(n log n) / O(n)Overkill when windows only slide
Kadane's algorithm (DP)Maximum-sum subarray of any lengthΘ(n)O(1)A length constraint is added (then combine with prefix sums or deques)

K.2 One problem, four solutions: "shortest subarray with sum ≥ K"

SolutionPositive numbersNegatives allowedTime
Brute force over all (L, R)✓✓Θ(n²) with running sums
Variable sliding window (I.4)✓✗ wrong answersΘ(n)
Prefix sums + binary search✓ (prefix sums increase)✗Θ(n log n)
Prefix sums + monotonic deque (LeetCode 862)✓✓Θ(n)

Why the window fails with negatives. Illustration Try [84, −37, 32, 40, 95], K = 167: the answer is [32, 40, 95] (sum 167, length 3). The sliding window becomes valid at R = 4 with sum 214, then shrinks: removing 84 gives 130, which is invalid, so it stops and reports length 5. It never tries dropping 84 and −37 together, because removing 84 alone made the sum smaller. The monotonic-deque solution in Section M handles this correctly.

K.3 When to avoid a sliding window

  • The answer may skip elements (subsequences): use DP, sorting or greedy methods instead.
  • The condition is not monotone in L for fixed R (sums with negatives, "exactly K" conditions — unless rewritten as atMost(K) − atMost(K−1)).
  • Many queries with arbitrary, unrelated ranges: use prefix sums, sparse tables or segment trees.
  • The window state cannot be updated cheaply (median without a balanced structure, or the full sorted order of the window).

LCommon mistakes and misconceptions

L.1 Hidden O(k) work inside the loop

✗ Looks like a window, is brute force
for i in range(n - k + 1):
    best = max(best, sum(a[i:i + k]))  # O(k) copy + sum
Θ(n·k): the slice copies k elements every iteration [11].
✓ Update, don't recompute
s = sum(a[:k]); best = s
for r in range(k, n):
    s += a[r] - a[r - k]
    best = max(best, s)
Θ(n).

L.2 if instead of while when shrinking

✗ Shrinks at most once per step
if len(count) > k:      # may still be invalid!
    count[a[L]] -= 1
    if count[a[L]] == 0: del count[a[L]]
    L += 1
total += R - L + 1
Counting windows with at most 1 distinct value in [1, 1, 2]: at R = 2 one removal leaves [1, 2], still invalid, and 2 is added. Result 5; the correct answer is 4.
✓ Repair until valid
while len(count) > k:
    count[a[L]] -= 1
    if count[a[L]] == 0: del count[a[L]]
    L += 1
total += R - L + 1
Gives 4 (verified by running both versions).

For "longest window" problems only, an if happens to give the right length: the window then never shrinks, only slides, and keeps the best size found so far. This "non-shrinking window" is a known trick, but the window it holds may be invalid, so it is wrong for counting, for "shortest" and for reporting the window itself. Use while unless you can explain why if is safe.

L.3 Forgetting to delete zero counts

count[x] -= 1 leaves the key in the dictionary with value 0, so len(count) still counts x as present. Either del count[x] at zero, or track a separate distinct integer that changes when a count goes 0 → 1 or 1 → 0.

L.4 Off-by-one in the window length and the full-window test

✗ Typical slips
length = R - L          # one too small
if R >= k:  record()   # skips the first window
remove(a[R - k + 1])     # removes an element still inside
✓ Inclusive window [L, R]
length = R - L + 1
if R >= k - 1: record() # first full window at R = k-1
remove(a[R - k])         # the element that just left

L.5 Moving L backwards

In the last-seen trick, L = last_seen[ch] + 1 without the guard last_seen[ch] ≥ L (or without L = max(L, last_seen[ch] + 1)) fails on "abba": at the final a, last_seen is 0 while L is 2, so L would jump back to 1 and report length 3 instead of 2.

L.6 Using a list as the deque

window.pop(0) on a list is O(n) because every remaining element moves; collections.deque.popleft() is O(1) [9]. The bug is invisible on small tests and turns Θ(n) into Θ(n·k) on large ones.

L.7 Complexity misconceptions

  • "Nested loops mean O(n²)." Not when the inner loop advances a pointer that never resets. The inner while runs at most n times in total (G.3).
  • "The deque solution is O(n·k) because one step can pop k elements." Each element is popped at most once overall, so the total is O(n) (G.4).
  • "Sliding window is O(1) space." Only for invertible aggregates. Count maps need O(Σ); deques need O(k).
  • "NumPy's sliding_window_view makes it O(n)." The view is free; summing it is still Θ(n·k) arithmetic [12].

L.8 Interview mistakes

  • Not asking whether numbers can be negative or zero — this decides between a window and prefix sums.
  • Recording the answer in the wrong place (before repairing for "longest", after shrinking for "shortest").
  • Returning inf or float('inf') when no window exists instead of the specified 0 or −1.
  • Not stating the invariant out loud. Saying "after this loop, the window [L, R] is the widest valid window ending at R" earns credit even before the code works.

MInterview preparation

M.1 Questions interviewers actually ask

  1. Why is your two-pointer solution O(n) even though it has a nested loop? (Each pointer moves at most n times — G.3.)
  2. What changes if the array can contain negative numbers? (Validity stops being monotone; use prefix sums — K.2.)
  3. How would you get the maximum of every window in O(n)? (Monotonic deque — G.4.)
  4. How do you count subarrays with exactly K distinct values? (atMost(K) − atMost(K−1) — G.5.)
  5. Your data arrives as an unbounded stream. What do you store? (Only the window: a bounded deque, or counters/sketches if even that is too large — J, N.)

M.2 Recognition signals

Phrase in the problemLikely pattern
"every k consecutive", "window of size k", "each day's last k days"Fixed window
"longest substring / subarray such that …"Variable window, Template 2
"shortest / minimum length subarray with sum ≥ …" (positives)Variable window, Template 3
"number of subarrays where …" (at most / less than)Variable window, Template 4
"exactly K …"atMost(K) − atMost(K−1)
"maximum / minimum in every window"Monotonic deque
"sum equals K", negatives allowedPrefix sums + hash map (Chapter 03)
"permutation / anagram of p inside s"Fixed window of length |p| + frequency table

M.3 Practice problems (with hints before solutions)

Problem statements are on LeetCode [22]. All solutions below were run against the official examples and against brute force on thousands of random inputs.

1. Maximum Average Subarray I EASY · LeetCode 643
Given nums and k, return the maximum average of a contiguous subarray of length k.
HintMaximising the average of a fixed-length window is the same as maximising its sum; divide once at the end.
Solution · Θ(n) time, O(1) space
def find_max_average(nums, k):                      # LC 643
    window = best = sum(nums[:k])
    for r in range(k, len(nums)):
        window += nums[r] - nums[r - k]
        best = max(best, window)
    return best / k
2. Maximum Number of Vowels in a Substring of Given Length EASY · LeetCode 1456
HintThe window state is one integer: the number of vowels inside. In Python, a bool behaves as 0 or 1 in arithmetic.
Solution · Θ(n) time, O(1) space
def max_vowels(s, k):                               # LC 1456
    V = set("aeiou")
    cur = sum(c in V for c in s[:k]); best = cur
    for r in range(k, len(s)):
        cur += (s[r] in V) - (s[r - k] in V)
        best = max(best, cur)
    return best
3. Longest Repeating Character Replacement MEDIUM · LeetCode 424
You may change up to k characters; return the longest substring of one repeated letter you can make.
Hint 1A window is fixable if length − (count of its most frequent letter) ≤ k.
Hint 2max_freq never needs to decrease: a smaller value can never produce a longer answer than one already recorded.
Solution · Θ(n) time, O(Σ) space
def character_replacement(s, k):                    # LC 424
    count = Counter(); left = max_freq = best = 0
    for right, ch in enumerate(s):
        count[ch] += 1
        max_freq = max(max_freq, count[ch])
        while (right - left + 1) - max_freq > k:    # too many cells to repaint
            count[s[left]] -= 1
            left += 1
        best = max(best, right - left + 1)
    return best
4. Max Consecutive Ones III MEDIUM · LeetCode 1004
HintRephrase it: the longest window containing at most k zeros.
Solution · Θ(n) time, O(1) space
def longest_ones(nums, k):                          # LC 1004
    left = zeros = best = 0
    for right, x in enumerate(nums):
        zeros += x == 0
        while zeros > k:
            zeros -= nums[left] == 0
            left += 1
        best = max(best, right - left + 1)
    return best
5. Permutation in String MEDIUM · LeetCode 567  (see also LeetCode 438, Lab 4)
HintA fixed window of length |s1| over s2; compare letter counts.
Solution · Θ(n·Σ) with Counter comparison (Σ = 26), O(Σ) space
def check_inclusion(s1, s2):                        # LC 567
    k = len(s1)
    if k > len(s2): return False
    need, have = Counter(s1), Counter(s2[:k])
    if need == have: return True
    for r in range(k, len(s2)):
        have[s2[r]] += 1
        have[s2[r - k]] -= 1
        if have[s2[r - k]] == 0: del have[s2[r - k]]
        if have == need: return True
    return False
6. Fruit Into Baskets MEDIUM · LeetCode 904
HintThe longest window with at most 2 distinct values, in disguise.
Solution · Θ(n) time, O(1) space (at most 3 keys)
def total_fruit(fruits):                            # LC 904
    count = Counter(); left = best = 0
    for right, f in enumerate(fruits):
        count[f] += 1
        while len(count) > 2:
            count[fruits[left]] -= 1
            if count[fruits[left]] == 0: del count[fruits[left]]
            left += 1
        best = max(best, right - left + 1)
    return best
7. Minimum Window Substring HARD · LeetCode 76
Return the shortest substring of s that contains every character of t, with multiplicity.
Hint 1Template 3 (shortest valid). The window is valid when it covers t.
Hint 2Keep need[c] = how many more c are required (it can go negative for surplus) and one integer missing; the window is valid when missing == 0. That avoids comparing whole maps.
Solution · Θ(|s| + |t|) time, O(Σ) space
def min_window(s, t):                               # LC 76
    if not t or not s: return ""
    need = Counter(t); missing = len(t)             # characters still missing
    left = 0; best = (float("inf"), 0, 0)
    for right, ch in enumerate(s):
        if need[ch] > 0: missing -= 1
        need[ch] -= 1                               # may go negative = surplus
        if missing == 0:                            # window covers t
            while need[s[left]] < 0:                # drop surplus from the left
                need[s[left]] += 1
                left += 1
            if right - left + 1 < best[0]:
                best = (right - left + 1, left, right + 1)
            need[s[left]] += 1                      # give up one required char
            missing += 1
            left += 1
    return "" if best[0] == float("inf") else s[best[1]:best[2]]
8. Sliding Window Maximum HARD · LeetCode 239
HintA heap gives O(n log n). For O(n), which elements can never be a future maximum?
SolutionExactly sliding_window_max from I.6 · Θ(n) time, O(k) space. Try it in Lab 3.
9. Subarrays with K Different Integers HARD · LeetCode 992
Hint"Exactly K" is not monotone; "at most K" is (G.5).
Solution · Θ(n) time, O(n) space
def subarrays_with_k_distinct(nums, k):             # LC 992
    def at_most(k):
        if k < 0: return 0
        count = Counter(); left = total = 0
        for right, x in enumerate(nums):
            count[x] += 1
            while len(count) > k:
                count[nums[left]] -= 1
                if count[nums[left]] == 0: del count[nums[left]]
                left += 1
            total += right - left + 1
        return total
    return at_most(k) - at_most(k - 1)
10. Shortest Subarray with Sum at Least K (negatives allowed) HARD · LeetCode 862
Hint 1Work on prefix sums P. You want the largest i < j with P[j] − P[i] ≥ K.
Hint 2If P[i₁] ≥ P[i₂] with i₁ < i₂, then i₁ is never a better start than i₂, so keep the start candidates in a deque with increasing P. Once a start has served some j, it can be discarded, because later j's would only give longer subarrays.
Solution · Θ(n) time, O(n) space
def shortest_subarray(nums, k):                     # LC 862 (negatives allowed)
    P = [0, *accumulate(nums)]                      # prefix sums, P[0] = 0
    dq = deque(); best = float("inf")
    for j, pj in enumerate(P):
        while dq and pj - P[dq[0]] >= k:            # best start for this end found
            best = min(best, j - dq.popleft())
        while dq and P[dq[-1]] >= pj:               # keep prefix values increasing
            dq.pop()
        dq.append(j)
    return -1 if best == float("inf") else best

M.4 Pattern: deque-optimised dynamic programming

When a DP transition takes the best value from a sliding range of earlier states — dp[i] = nums[i] + max(dp[i−k..i−1]) — the range maximum is a sliding-window maximum, and the DP drops from O(n·k) to O(n). LeetCode 1696 (Jump Game VI) is the standard example [22]:

def max_result(nums, k):                            # LC 1696 Jump Game VI (deque DP)
    dp = [0] * len(nums); dp[0] = nums[0]; dq = deque([0])
    for i in range(1, len(nums)):
        if dq[0] < i - k: dq.popleft()
        dp[i] = nums[i] + dp[dq[0]]
        while dq and dp[dq[-1]] <= dp[i]: dq.pop()
        dq.append(i)
    return dp[-1]

★Practice problems

Decide first whether the window has a fixed size or grows and shrinks, and what state you must keep as it moves. There are 29 problems, grouped by level and topic: 7 easy, 16 medium and 6 hard. Each link opens the problem on the platform where you can submit and test your solution. Tick a problem when you have solved it, and use “My solution” to save your code, approach, complexity and notes to revise later.

Level
Difficulty
0 / 29 solved
Saved in this browser

Basic6 problems

Direct applications of this chapter’s core idea.

Sliding Window

Fixed and variable windows that update incrementally as they move.

  1. Max Sum Subarray of Size K⤢EASYGeeksforGeeks
  2. Fence (Codeforces)⤢EASYCodeforces
  3. Maximum Average Subarray I⤢EASYLeetCode
  4. Find the K-Beauty of a Number⤢EASYLeetCode
  5. Defuse the Bomb⤢EASYLeetCode

Intermediate17 problems

The pattern combined with one more idea, or applied to a less obvious setup.

Sliding Window

Fixed and variable windows that update incrementally as they move.

  1. Minimum Size Subarray Sum⤢MEDIUMLeetCode
  2. Fruit Into Baskets⤢MEDIUMLeetCode
  3. Permutation in String⤢MEDIUMLeetCode
  4. Find All Anagrams in a String⤢MEDIUMLeetCode
  5. Max Consecutive Ones III⤢MEDIUMLeetCode
  6. Binary Subarrays With Sum⤢MEDIUMLeetCode
  7. Get Equal Substrings Within Budget⤢MEDIUMLeetCode
  8. Subarray Product Less Than K⤢MEDIUMLeetCode
  9. Count the Number of Good Subarrays⤢MEDIUMLeetCode
  10. Count Zero Request Servers⤢MEDIUMLeetCode

Advanced6 problems

Harder variants that need the full toolkit and careful invariants.

Sliding Window

Fixed and variable windows that update incrementally as they move.

  1. Minimum Window Substring⤢HARDLeetCode
  2. Count Complete Substrings⤢HARDLeetCode

NAdvanced concepts

N.1 Any associative aggregate: the two-stack queue

The deque trick is specific to min and max. For any associative operation — gcd, bitwise AND/OR, matrix products — a window can be kept as a queue built from two stacks, where each stack entry also stores the aggregate of itself and everything below it. Push onto the "in" stack; pop from the "out" stack; when "out" is empty, move everything across, which reverses the order. The window aggregate is the combination of the two stack tops. Each element moves between stacks once, so every operation is amortized O(1) [4]. Unlike the deque method, this needs no inverse and no ordering — only associativity.

from math import gcd

class AggQueue:
    """Queue with O(1) amortized push, pop and aggregate for an associative op."""
    def __init__(self, op):
        self.op, self.inn, self.out = op, [], []   # stacks of (value, aggregate)
    def push(self, x):
        agg = x if not self.inn else self.op(self.inn[-1][1], x)
        self.inn.append((x, agg))
    def pop(self):
        if not self.out:                           # move and reverse
            while self.inn:
                x, _ = self.inn.pop()
                agg = x if not self.out else self.op(x, self.out[-1][1])
                self.out.append((x, agg))
        return self.out.pop()[0]
    def query(self):
        parts = [s[-1][1] for s in (self.out, self.inn) if s]
        return parts[0] if len(parts) == 1 else self.op(parts[0], parts[1])

# gcd of every window of size 3 in [12, 18, 24, 9, 27, 36]  ->  [6, 3, 3, 9]

The order inside op(...) keeps "older on the left" for operations that are associative but not commutative, such as matrix products. The example output was verified by running the class.

N.2 Size-independent running max/min: van Herk / Gil–Werman

Split the array into blocks of length k. Inside each block compute prefix maxima left-to-right (g) and suffix maxima right-to-left (h). Any window of length k crosses at most one block boundary, so its maximum is max(h[i], g[i+k−1]). That is O(1) per window with no data-dependent branching, which suits vector hardware and image filters [19][20]. Lemire later gave a streaming variant that uses no more than three comparisons per element [20].

N.3 Order statistics: sliding median and k-th largest

The median has no O(1) update. Standard approaches keep the window in two heaps (a lower max-heap and an upper min-heap) with lazy deletion, or in a balanced binary search tree or sorted container, for O(log k) per slide and O(n log k) overall. LeetCode 480 (Sliding Window Median) is the usual exercise.

N.4 Two-dimensional windows

The maximum over every k×k block of an image is separable: first run the 1-D window maximum along every row, then along every column of that result. The cost is O(rows·cols) whatever k is, which is how a rectangular dilation can be computed in time independent of the structuring element's size [21]. Sums over 2-D windows are easiest with a 2-D prefix-sum table (Chapter 03).

N.5 Streaming windows in sub-linear memory

Sometimes even the window is too large to store — think of counting the 1s in the last billion bits of a network stream. Datar, Gionis, Indyk and Motwani's exponential histograms keep buckets whose sizes are powers of two and approximate the count within a factor 1 ± ε using O((1/ε) log² N) bits, and they show this is essentially optimal [17]. Mining of Massive Datasets (Stanford) teaches the same algorithm under the name DGIM [18]. The general lesson: exact sliding windows need memory proportional to the window, and approximation buys space, just as Cloudflare's two-counter estimate does [14].

N.6 Time-based and event-time windows

In production, windows are often defined by time ("last 5 minutes") rather than by count, and events can arrive out of order. Stream processors such as Flink distinguish tumbling, sliding, session and global windows and let you choose processing time or event time [15]. The algorithmic core is unchanged — evict what fell out of the window, fold in what arrived — but eviction is now driven by timestamps and watermarks instead of by an index.

ONotebook-ready summary

First, the whole idea on one page — copy this sheet into your notebook. The detailed revision notes follow it.

Sliding Window
Reuse the previous window: add what enters, remove what leaves — Θ(n) instead of Θ(n·k) or Θ(n²)
What is it?

A contiguous range [L, R] moved left → right. Both pointers only move forward; a small state (sum / counts / deque) is updated in O(1) per move.

Fixed size k
S′ = S − a[L] + a[R+1]
1out
5
1
3in
2

first full window at R = k − 1 · drop a[R − k]

Variable size
  • longest: while invalid → shrink; then record
  • shortest: while valid → record, shrink
  • count: total += R − L + 1
  • exactly K = atMost(K) − atMost(K−1)
Watch out!
  • negatives + sum target → prefix sums
  • length = R − L + 1
  • while, not if, when repairing
  • delete zero counts · no slicing in the loop
Complexity
AlgorithmTimeSpace
brute forceΘ(n·k)O(1)
fixed, sumΘ(n)O(1)
variable (2 ptr)Θ(n)O(1)–O(Σ)
window max/minΘ(n)O(k) deque
heap maxO(n log n)O(n)
sliding medianO(n log k)O(k)

why Θ(n)? L and R each move ≤ n times → ≤ 2n steps (amortized)

Monotonic deque (max)
pop back while a[back] ≤ x → push R
pop front if index ≤ R − k → answer a[front]
5front
3
1back

values decreasing · indices increasing · each pushed once, popped ≤ once

Used in

TCP send window · rate limiters · Flink windows · SQL ROWS BETWEEN · Rabin–Karp · image dilation

Templates
Fixed k
for R, x in enumerate(a):
    s += x
    if R >= k: s -= a[R-k]
    if R >= k-1: best = max(best, s)
Θ(n) · O(1) space
Longest valid
L = 0
for R, x in enumerate(a):
    add(x)
    while invalid(): remove(a[L]); L += 1
    best = max(best, R-L+1)
≤ 2n moves → Θ(n)
Shortest valid
L = 0
for R, x in enumerate(a):
    add(x)
    while valid():
        best = min(best, R-L+1)
        remove(a[L]); L += 1
positives only → Θ(n)
Window max
for R, x in enumerate(a):
    while dq and a[dq[-1]] <= x: dq.pop()
    dq.append(R)
    if dq[0] <= R-k: dq.popleft()
    if R >= k-1: out.append(a[dq[0]])
deque of indices · Θ(n)

Detailed revision notes

1 · Formal definition

A window is [L, R], 0 ≤ L ≤ R < n, length R − L + 1. A sliding-window algorithm visits windows with non-decreasing L and R and keeps a state updated by add(a[R]) / remove(a[L]).

2 · Core concept

Neighbouring windows share k − 1 elements → update instead of recompute. Fixed: S′ = S − a[L] + a[R+1] (needs an inverse). Variable: grow with R, repair with L.

3 · Key properties

① each pointer moves ≤ n times → ≤ 2n state updates → Θ(n) amortized.
② variable windows need a monotone condition (shrink-closed: sub-window of valid is valid).
③ L*(R) is non-decreasing (staircase picture, Fig. G.1).
④ count valid windows ending at R = R − L + 1.

4 · Operations & state

sum/count/xor → 1 integer · distinct/anagram → dict of counts (delete zeros!) · max/min → monotonic deque of indices · gcd/AND/OR → two-stack queue.

5 · Python syntax

from collections import deque, Counter
dq.append(i); dq.pop(); dq.popleft(); dq[0]; dq[-1]
deque(maxlen=k) = last k items · itertools.pairwise = k = 2
never sum(a[i:i+k]) in the loop · never list.pop(0)

6 · Applications

TCP send window (SND.UNA … SND.UNA+SND.WND) · rate limit ≈ prev × overlap + curr · Flink sliding windows · SQL frames · Rabin–Karp rolling hash · running max/min image filters.

7 · Interview takeaways

Ask "can values be negative?" first · say the invariant aloud · "exactly K" = atMost(K) − atMost(K−1) · "max in every window" = deque · return the specified sentinel (0 / −1 / "").

PKnowledge assessment

Try everything here before opening the answer key in P.5.

P.1 Conceptual questions

  1. Why does the fixed-window update S′ = S − a[L] + a[R+1] work for sums and xor but not for maximum?
  2. The two-pointer template contains a while loop inside a for loop. Prove it is O(n), not O(n²).
  3. Give an example of a condition that is shrink-closed and one that is not, and explain why the difference matters.
  4. In the monotonic deque for window maxima, why do we store indices rather than values?
  5. A teammate proposes the variable window for "shortest subarray with sum ≥ K" on stock price changes, which can be negative. What do you tell them?

P.2 Dry-run exercises

  1. Run max_sum_fixed([4, −2, 3, 6, −1, 5], k = 2). Write the window sum after each step and the final answer.
  2. Run longest_at_most_k_distinct("aabacbebebe", k = 3). Report L, R and the best length at each R where L changes, and the final answer.
  3. Run sliding_window_max([9, 8, 7, 6, 5], k = 3). Show the deque after every step and mark each front expiry.

P.3 Coding problems

  1. Nearby duplicate. Return True if two equal values occur at indices i ≠ j with |i − j| ≤ k (LeetCode 219). Target: O(n) time, O(k) space.
  2. Small products. Given positive integers and k, count the contiguous subarrays whose product is strictly less than k (LeetCode 713). Target: O(n).
  3. Window spread. For every window of size k, output max − min. Target: O(n). Example: [4, 2, 12, 3, 8, 6], k = 3 → [10, 10, 9, 5].

P.4 Practical engineering scenario

Scenario: login abuse detector Your authentication service handles ~20,000 logins per second across 5 million user IDs. Security asks you to block an IP address for 10 minutes if it produces more than 30 failed logins in any 60-second period. Memory per instance is limited, and requests for one IP can reach any of 40 instances. Design the detector: which window (fixed, sliding log, sliding counter), what state per IP, where that state lives, and what the accuracy and memory trade-offs are.

P.5 Answer key

Conceptual answers
  1. The update removes the leaving element's contribution by applying an inverse: −x for +, x itself for xor (x ⊕ x = 0). Maximum has no inverse — knowing max(window) and the leaving value tells you nothing about the new maximum if the leaving value was the maximum — so a structure that remembers the runner-up candidates (the monotonic deque) is needed (G.1, G.4).
  2. R increases from 0 to n−1 once. L starts at 0, only increases, and never exceeds n, so across the entire run the while body executes at most n times. Total body executions ≤ n (for) + n (while) = 2n, each O(1) (aggregate amortized analysis, G.3).
  3. Shrink-closed: "at most K distinct", "no repeated character", "sum ≤ T with non-negative values". Not shrink-closed: "exactly K distinct", "sum ≥ T" (removing elements can make it invalid), "sum = T" with negatives. Shrink-closure makes L*(R) monotone, so L never needs to move back; without it, the correct left end can jump backwards and the two-pointer scan misses answers (G.2, K.2).
  4. To detect expiry: the front must leave when its position is ≤ R − k. With values only, duplicates make it impossible to tell which copy is leaving (CP-Algorithms' value-only variant must compare against the removed value, and the index-based variant avoids that) [4][2].
  5. With negative values, shrinking can increase the sum, so "valid" is not monotone and the window can stop shrinking too early — see the counterexample [84, −37, 32, 40, 95], K = 167 in K.2. Use prefix sums with a monotonic deque (LeetCode 862, Section M) for O(n).
Dry-run answers

1. Windows: [4,−2]=2 → [−2,3]=1 → [3,6]=9 → [6,−1]=5 → [−1,5]=4. Answer 9.

2. Distinct counts are kept in a Counter. L first moves at R = 6 ('e' makes 4 distinct {a,b,c,e}): L advances 0→1→2→3→4, removing a, a, b, a, until the window "cbe" has 3 distinct; best so far 6 (window "aabacb"). Then R = 7..10 add b, e, b, e with no change of L, ending with window "cbebebe" (L = 4, R = 10), length 7. Final answer 7.

3. R=0: [0]. R=1: 8 < 9, push → [0,1]. R=2: push → [0,1,2], output 9. R=3: push → [0,1,2,3]; front 0 ≤ 3−3 → expire 0 → [1,2,3], output 8. R=4: push → [1,2,3,4]; expire 1 → [2,3,4], output 7. Outputs [9, 8, 7]. Decreasing input is the case where expiry does all the work and nothing is popped from the back.

Coding answers (all tested against brute force)
def contains_nearby_duplicate(nums, k):             # LC 219 (assessment coding 1)
    window = set()
    for i, x in enumerate(nums):
        if x in window: return True
        window.add(x)
        if len(window) > k: window.remove(nums[i - k])
    return False

Fixed window kept as a set of the last k values · O(n) expected time, O(k) space.

def count_subarrays_product_less(nums, k):          # LC 713 (assessment coding 2)
    if k <= 1: return 0
    prod = 1; left = total = 0
    for right, x in enumerate(nums):
        prod *= x
        while prod >= k:
            prod //= nums[left]; left += 1
        total += right - left + 1
    return total

Template 4 with a running product. Positive integers make "product < k" shrink-closed · O(n).

def sliding_window_min_range(nums, k):              # assessment coding 3: max-min per window
    mx, mn, out = deque(), deque(), []
    for r, x in enumerate(nums):
        while mx and nums[mx[-1]] <= x: mx.pop()
        while mn and nums[mn[-1]] >= x: mn.pop()
        mx.append(r); mn.append(r)
        if mx[0] <= r - k: mx.popleft()
        if mn[0] <= r - k: mn.popleft()
        if r >= k - 1: out.append(nums[mx[0]] - nums[mn[0]])
    return out

Two monotonic deques, one for the maximum and one for the minimum · O(n) time, O(k) space.

Engineering scenario: a model answer
  1. Window choice. A fixed-window counter (reset each minute) lets an attacker send 30 failures at 0:59 and 30 more at 1:00 — 60 in two seconds — without tripping the rule. A sliding log of timestamps is exact but costs one entry per failure. A sliding counter stores two integers per IP (previous and current minute) and estimates prev × (1 − elapsed/60) + curr, which is the approach Cloudflare measured as very accurate at scale [14].
  2. State placement. Requests for an IP reach any instance, so per-instance memory sees only part of the traffic — the same problem Cloudflare describes for edge servers [14]. Keep the counters in a shared store keyed by (ip, minute), using atomic increments and a TTL of about two minutes, so old minutes expire on their own.
  3. Memory. Two small integers per active IP rather than up to 30+ timestamps; only IPs with recent failures have keys at all.
  4. Accuracy. The estimate assumes failures in the previous minute were evenly spread, so it can be slightly off near the threshold. For a security block that is usually acceptable; if exactness matters for a small set of suspicious IPs, switch just those to a sliding log (a deque of timestamps, evicting entries older than 60 s — Template 1 driven by time).
  5. Block action. When the estimate exceeds 30, write a blocked:ip key with a 10-minute TTL and check it before any password verification.

QReferences and further reading

  1. A. Laaksonen, Competitive Programmer's Handbook (draft), Chapter 8 "Amortized analysis": §8.1 Two pointers method, §8.3 Sliding window minimum. Definition of a sliding window, two-pointer method with monotone pointers, amortized O(n) arguments (Sections A, B, C, D, F, G, H).
  2. USACO Guide (Competitive Programming Initiative), Sliding Window. Quotes the CPH definition; variable-size windows with both endpoints moving right; decreasing monotonic deque with indices for the window maximum (Sections B, C, F, I, P).
  3. USACO Guide, Two Pointers. Two variants of two pointers (opposite ends; same direction = sliding window) (Sections B, D, F, K).
  4. CP-Algorithms, Minimum stack / Minimum queue. Deque-based minimum queue, the two-stack queue, amortized O(1) operations, minimum of all fixed-length subarrays in O(n) (Sections B, C, D, F, G, H, N, P).
  5. T. H. Cormen, C. E. Leiserson, R. L. Rivest, C. Stein, Introduction to Algorithms, 4th ed., MIT Press, 2022. Aggregate amortized analysis (Ch. 16) and the Rabin–Karp algorithm (Ch. 32) (Sections B, G, H, J).
  6. R. Sedgewick, K. Wayne, Algorithms, 4th ed., §5.3 Substring Search, Princeton University. RabinKarp.java fingerprint algorithm; exercise on searching for multiple equal-length patterns via a set of hashes (Sections B, G, J).
  7. R. Sedgewick, K. Wayne, Princeton COS 226 lecture slides, 5.3 Substring Search. Applications of substring search; brute force ~MN worst case; Rabin–Karp (Sections G, J).
  8. R. M. Karp, M. O. Rabin, "Efficient randomized pattern-matching algorithms", IBM Journal of Research and Development 31(2), 1987. Original rolling-fingerprint pattern matching (Sections B, G, J).
  9. Python Software Foundation, collections.deque. ≈O(1) appends/pops at both ends; O(n) list pop(0)/insert(0, v); maxlen eviction; O(n) middle indexing (Sections F, H, I, L).
  10. Python Software Foundation, itertools — pairwise (3.10) and the sliding_window recipe. Built-in alternatives (Section I.11).
  11. Python Wiki, TimeComplexity. Costs of list slicing (O(k)), dict operations (O(1) average) used in Sections F, H, L.
  12. NumPy Developers, numpy.lib.stride_tricks.sliding_window_view (new in 1.20.0). Window views without copying, and the performance note about generic window reductions (Sections H, I, L).
  13. W. Eddy (ed.), RFC 9293: Transmission Control Protocol (TCP), IETF, 2022. Window field (§3.1), SND.UNA/SND.NXT/SND.WND and the send-sequence-space figure (§3.3.1); obsoletes RFC 793 (Sections B, J).
  14. Cloudflare, "How we built rate limiting capable of scaling to millions of domains", 2017. Two-counter sliding-window estimate, worked example, accuracy on 400M requests, memory argument (Sections J, N, P).
  15. Apache Software Foundation, Apache Flink documentation: Windows. Tumbling, sliding, session and global windows; size and slide; overlap assigns elements to several windows (Sections J, N).
  16. PostgreSQL Global Development Group, §4.2.8 Window Function Calls. Frame clause syntax and semantics; smaller frames near partition ends (Section J).
  17. M. Datar, A. Gionis, P. Indyk, R. Motwani, "Maintaining stream statistics over sliding windows", SIAM Journal on Computing 31(6):1794–1813, 2002. The sliding-window streaming model, exponential histograms, O((1/ε) log² N) bits (Sections B, H, J, N).
  18. J. Leskovec, A. Rajaraman, J. D. Ullman, Mining of Massive Datasets, Ch. 4 "Mining Data Streams", Cambridge University Press (Stanford). Approximate counting of 1s in a window of a bit stream (DGIM) (Sections B, N).
  19. M. van Herk, "A fast algorithm for local minimum and maximum filters on rectangular and octagonal kernels", Pattern Recognition Letters 13(7):517–521, 1992. Window-size-independent running max/min (Sections B, J, N).
  20. D. Lemire, "Streaming Maximum-Minimum Filter Using No More than Three Comparisons per Element", arXiv:cs/0610046. Describes the van Herk/Gil–Werman block algorithm and a streaming improvement (Sections J, N).
  21. S. Eddins, MathWorks Blogs, "Dilation with linear structuring elements" (Steve on Image Processing), 31 Dec 2008. imdilate/imerode use van Herk's algorithm; time independent of rectangular structuring element size (Sections J, N).
  22. LeetCode problem statements: 3, 76, 209, 239, 424, 438, 480, 567, 643, 862, 904, 992, 1004, 1456, 1696. Original problem statements for the examples and exercises (Sections C, D, G, M, N, P).
  23. B. Babcock, S. Babu, M. Datar, R. Motwani, J. Widom, "Models and Issues in Data Stream Systems", PODS 2002 (Stanford University). Sliding-window queries in data stream management systems (Section J).

Further reading: UCSD ICPC's Two Pointers, Sliding Window, Merge Intervals slides, give more practice in the same style.