AlgoViz

Sliding window (fixed size)

medium 18 min

A fixed sliding window looks at every run of exactly k neighbouring items.

Video lesson · Chapter 1 of 8

Three minute signal

0:00 / 5:58

Fixed window

1:07Reel

How it works

Step through the idea, or press Play.

Step 1 of 3

Build the first window. Read items 0 to k - 1 once and set up the state: a sum, a count map or a deque

Understand it

Start here

The problem: every run of k in a row

Many questions ask about every block of exactly k neighbouring items: the best 7-day total, the busiest 5-minute stretch, every 3-letter chunk that is an anagram of a word. For nums = [2, 1, 5, 1, 3, 2] and k=3k = 3 the blocks are [2, 1, 5], [1, 5, 1], [5, 1, 3] and [1, 3, 2], and the largest sum is 9 from [5, 1, 3]. A list of nn items has n−k+1n - k + 1 such windows.

What this topic builds on

  • Two pointers

    The window is two indexes, L and R, that only move forward. See Two pointers.

  • Hash maps

    Counting letters or values inside a window is a dict of counts. See Hash usage.

  • Queues and deques

    The window maximum keeps candidates in a deque, adding at the back and removing at both ends. See Queue.

The life of a fixed window
  1. 1Enternums[i] joins at the right edge
  2. 2Leavenums[i - k] drops off the left edge
  3. 3RecordUpdate the answer for the window i - k + 1 to i
Repeat: back to Enter

The window always holds exactly $k$ items: one in, one out, every step.

Brute force

Re-adding the same numbers: O(n · k)

Python
def max_sum_brute(nums, k):    best = float("-inf")    reads = 0    for start in range(len(nums) - k + 1):        total = 0        for j in range(start, start + k):            total += nums[j]            reads += 1        best = max(best, total)    return best, readsprint(max_sum_brute([2, 1, 5, 1, 3, 2], 3))    # (9, 12)print(max_sum_brute(list(range(1000)), 500))   # reads: 250500
Sum every window from scratch. Correct, and it counts its own reads.
Edit and run it in your browser

How many reads brute force makes

Rbrute(n,k)=(n−k+1)⏟windows⋅k⏟reads each  ≤  (n+12)2R_{\text{brute}}(n, k) = \underbrace{(n - k + 1)}_{\text{windows}} \cdot \underbrace{k}_{\text{reads each}} \;\le\; \left(\frac{n+1}{2}\right)^{2}
The product is largest when k≈n/2k \approx n/2, so the worst case is about n2/4n^2/4: quadratic. For n=1,000n = 1{,}000 and k=500k = 500 that is 250,500 reads.

The trick

Add one, drop one

The sliding update

Wi=∑j=i−k+1iaj⟹Wi=Wi−1+ai⏟enters−ai−k⏟leavesW_i = \sum_{j=i-k+1}^{i} a_j \quad\Longrightarrow\quad W_i = W_{i-1} + \underbrace{a_i}_{\text{enters}} - \underbrace{a_{i-k}}_{\text{leaves}}
WiW_i is the sum of the window that ends at index ii. Subtract the two sums and every shared term cancels, leaving one item in and one item out. In code: window += nums[i] - nums[i - k].

The fixed-window loop

Build once, then Subtract, Add, Update on every step. The old app's mnemonic: S-A-U.

Sliding over [2, 1, 5, 1, 3, 2] with k = 3

iLeavesEntersWindowSumbest
0 to 2–2, 1, 5[2, 1, 5]88
321[1, 5, 1]8 − 2 + 1 = 78
413[5, 1, 3]7 − 1 + 3 = 99
552[1, 3, 2]9 − 5 + 2 = 69
Three slides of two reads each after a first window of three reads: 9 reads instead of 12.

Cost

Why it is O(n) time and O(1) space

Reads made by the slide

Rslide(n,k)=k⏟first window+2(n−k)⏟one in, one out per slide=2n−k  ≤  2n=O(n)R_{\text{slide}}(n, k) = \underbrace{k}_{\text{first window}} + \underbrace{2(n - k)}_{\text{one in, one out per slide}} = 2n - k \;\le\; 2n = O(n)
Each item is added once and removed at most once, whatever kk is. The state is two numbers, window and best, so the extra space is O(1)O(1).
nkBrute force readsSliding readsSaving
631291.3×
100109101904.8×
1,000500250,5001,500167×
100,0001,00099,001,000199,000497×
The bigger kk gets, the more brute force re-reads. The slide never reads more than 2n2n.

Template

Maximum sum and maximum average of k

Python
def max_sum_k(nums, k):    if k <= 0 or k > len(nums):        return None                       # no full window    window = sum(nums[:k])                # build the first window    best = window                         # not 0: sums can be negative    for i in range(k, len(nums)):         # i is the entering index        window += nums[i] - nums[i - k]   # add one, drop one        best = max(best, window)    return bestdef max_average_k(nums, k):    best = max_sum_k(nums, k)    return None if best is None else best / kprint(max_sum_k([2, 1, 5, 1, 3, 2], 3))          # 9print(max_average_k([1, 12, -5, -6, 50, 3], 4))  # 12.75print(max_sum_k([4, -1, 2, -3, 5, 1], 3))        # 5
The template. The maximum average is the maximum sum divided by k once, at the end.
Edit and run it in your browser

Edge cases

The inputs that break careless code

InputkWindow sumsAnswerWhat it tests
[2, 1, 5, 1, 3, 2]38, 7, 9, 69The standard case: best in the middle
[4, 4, 4, 4, 4]28, 8, 8, 88Ties: > keeps the first best window
[1, 2, 3, 4, 5, 6]36, 9, 12, 1515Best is the last window: loop to n−1n - 1
[4, −1, 2, −3, 5, 1]35, −2, 4, 35Negatives: best is the first window, not 0
[1, 3, 2, 5, 1, 2, 3, 4]411, 11, 10, 11, 1011Large k: only n−k+1=5n - k + 1 = 5 windows
[3, 8, 1]4noneNonek>nk > n: no window fits
The old app's five worked inputs plus the guard case. All six run in the visualizer's tricky inputs tab.

Guarding the input

sum(nums[:k]) never raises: with k>nk > n it silently sums a short window. Check first.

Do

  • Loop the entering index over range(k, len(nums)): that is n−kn - k slides.
  • Start best at the first window's sum.
  • Use the window that ends at i: it spans i - k + 1 to i.
  • Record an answer only once the window holds kk items (i >= k - 1).

Don't

  • Write range(k, len(nums) - 1) and lose the last window.
  • Start best at 0 when values can be negative.
  • Subtract nums[i - k + 1]: that item is still inside the window.
  • Call sum(nums[i:i + k]) in the loop: that is the brute force again.

Counts in a window

A hash map of counts: anagrams and permutations

An anagram of p inside s is a window of length len(p) with the same letter counts, in any order. Keep have, a dict of counts for the current window, and compare it with need, the counts of p. Entering letter: count up. Leaving letter: count down, and delete the key at 0 so the two dicts can be equal. For s = "cbaebabacd", p = "abc" the anagrams start at 0 ("cba") and 6 ("bac").

One step of the anagram scan

Comparing two dicts of at most 26 letters is O(1)O(1), so the whole scan is O(n)O(n) with O(1)O(1) extra space.
Python
def find_anagrams(s, p):    k = len(p)    need = {}    for ch in p:        need[ch] = need.get(ch, 0) + 1    have, out = {}, []    for i, ch in enumerate(s):        have[ch] = have.get(ch, 0) + 1          # enters        if i >= k:            old = s[i - k]                      # leaves            have[old] -= 1            if have[old] == 0:                del have[old]        if have == need:            out.append(i - k + 1)    return outdef contains_permutation(s, p):    return len(find_anagrams(s, p)) > 0         # or return at the first matchprint(find_anagrams("cbaebabacd", "abc"))       # [0, 6]print(find_anagrams("abab", "ab"))              # [0, 1, 2]print(contains_permutation("eidbaooo", "ab"))   # Trueprint(contains_permutation("eidboaoo", "ab"))   # False
All anagram starts, and the yes/no version (permutation in a string), from one loop.
Edit and run it in your browser

Sets and counters

Duplicates, distinct values and vowels

  • Duplicate within k

    Keep a set of the last kk values. If the entering value is already in it, two equal values sit at most kk apart. Drop nums[i - k] as it leaves.

  • Distinct values per window

    A dict of counts; the answer for each window is len(counts), as long as zero counts are deleted.

  • Vowels in a substring of k

    The state is one integer: +1 if the entering letter is a vowel, −1 if the leaving letter was one. Track the max.

Python
def has_nearby_duplicate(nums, k):    window = set()                      # holds at most k values    for i, x in enumerate(nums):        if x in window:            return True        window.add(x)        if len(window) > k:            window.remove(nums[i - k])  # the value k steps back leaves    return Falsedef distinct_per_window(nums, k):    counts, out = {}, []    for i, x in enumerate(nums):        counts[x] = counts.get(x, 0) + 1        if i >= k:            old = nums[i - k]            counts[old] -= 1            if counts[old] == 0:                del counts[old]        if i >= k - 1:            out.append(len(counts))    return outdef max_vowels(s, k):    vowels = set("aeiou")    count = sum(ch in vowels for ch in s[:k])    best = count    for i in range(k, len(s)):        count += (s[i] in vowels) - (s[i - k] in vowels)        best = max(best, count)    return bestprint(has_nearby_duplicate([1, 2, 3, 1], 3))        # True: the 1s are 3 apartprint(has_nearby_duplicate([1, 2, 3, 1, 2, 3], 2))  # Falseprint(distinct_per_window([1, 2, 1, 3, 4, 2, 3], 4))  # [3, 4, 4, 3]print(max_vowels("abciiidef", 3))                    # 3
Three windows whose state is a set, a dict and a single counter.
Edit and run it in your browser

Window maximum

Sliding window maximum with a monotonic deque

A sum can be undone by subtraction; a maximum cannot. When the max leaves the window, which value takes over? Calling max() on each window is O(n⋅k)O(n \cdot k). A heap works in O(nlog⁡n)O(n \log n) but needs lazy deletes. The best answer keeps a deque of indexes whose values fall from front to back. The front is always the max of the current window. For [1, 3, -1, -3, 5, 3, 6, 7] with k=3k = 3 the maxima are [3, 3, 5, 5, 6, 7].

One step of the deque

A newcomer evicts every smaller value in front of it: those are older and smaller, so they leave the window first and can never beat it.
Python
from collections import dequedef max_sliding_window(nums, k):    dq = deque()                       # indexes; values fall front to back    out = []    for i, x in enumerate(nums):        if dq and dq[0] <= i - k:      # front has left the window            dq.popleft()        while dq and nums[dq[-1]] <= x:            dq.pop()                   # smaller and older: never a max again        dq.append(i)        if i >= k - 1:            out.append(nums[dq[0]])    return outprint(max_sliding_window([1, 3, -1, -3, 5, 3, 6, 7], 3))   # [3, 3, 5, 5, 6, 7]print(max_sliding_window([9, 8, 7, 6], 2))                 # [9, 8, 7]
LeetCode 239, Sliding Window Maximum. Flip <= to >= for the window minimum.
Edit and run it in your browser

Deque trace for [1, 3, −1, −3, 5, 3, 6, 7], k = 3

ixExpiredPopped from backDeque (index:value)Output
01––0:1–
13–0:11:3–
2−1––1:3, 2:−13
3−3––1:3, 2:−1, 3:−33
451:33:−3, 2:−14:55
53––4:5, 5:35
66–5:3, 4:56:66
77–6:67:77
8 pushes and 7 pops for 8 items. The front is always the answer.

Proof

Why the deque is O(n), and why it is correct

Amortised cost

∑i=0n−1(1+popsi)  ≤  n⏟pushes+n⏟each index popped at most once  =  2n=O(n)\sum_{i=0}^{n-1} \big(1 + \text{pops}_i\big) \;\le\; \underbrace{n}_{\text{pushes}} + \underbrace{n}_{\text{each index popped at most once}} \;=\; 2n = O(n)
The inner while can pop several items in one step, but an index is pushed once and can only be removed once, so across the whole run the pops total at most nn. The deque never holds more than kk indexes: O(k)O(k) space.
ApproachTimeSpaceNotes
max() on every windowO(n⋅k)O(n \cdot k)O(1)O(1)Fine for tiny kk, quadratic in the worst case
Max-heap with lazy deletesO(nlog⁡n)O(n \log n)O(n)O(n)Pop the top while its index is outside the window
Monotonic dequeO(n)O(n)O(k)O(k)The interview answer
The heap version reuses Heap operations; the deque is the one to write.

Pattern map

Fixed window, variable window, prefix sums or two pointers?

Choosing the technique

Fixed windows work with negative numbers because the size is set; variable windows need a monotone condition to know when to shrink.

When the window size is not given and you must find the longest or shortest window that satisfies a rule, the left edge moves only when needed: that is the variable sliding window. When you need the sum of many arbitrary ranges rather than one sweep, precompute prefix sums: a fixed window sum is then Pi+1−Pi−k+1P_{i+1} - P_{i-k+1}, the same subtraction in another form. Both edges of a sliding window only move forward, which makes it a special case of two pointers.

Classic fixed-window problems

ProblemWindow stateCost
643 Maximum Average Subarray IRunning sumO(n)O(n), O(1)O(1)
1343 Subarrays of size k with average at least a thresholdRunning sum, count windowsO(n)O(n), O(1)O(1)
1456 Maximum vowels in a substring of length kVowel counterO(n)O(n), O(1)O(1)
219 Contains Duplicate IISet of the last k valuesO(n)O(n), O(k)O(k)
438 Find All Anagrams / 567 Permutation in StringLetter countsO(n)O(n), O(1)O(1)
2461 Max sum of distinct subarrays of length kRunning sum + countsO(n)O(n), O(k)O(k)
1423 Max points from cardsWindow of n − k on the middle (the complement)O(n)O(n), O(1)O(1)
239 Sliding Window MaximumMonotonic deque of indexesO(n)O(n), O(k)O(k)

Recap

What to remember

Key points

  • A fixed window covers exactly k neighbouring items; a list of n has n − k + 1 of them.
  • Brute force re-reads k items per window, O(n · k), about n²/4 in the worst case.
  • Slide instead: window += nums[i] − nums[i − k]. Each item enters once and leaves once, O(n) time.
  • Start best at the first window, loop i over range(k, n), guard k > n, record once i ≥ k − 1.
  • Counts in a window: a dict with zero keys deleted, compared with the pattern's counts (anagrams, permutations).
  • Window maximum: a deque of indexes with falling values; front is the answer, every index is pushed and popped at most once.
  • Size given: fixed window. Size to find: variable window. Many range queries: prefix sums.

Sources