Sliding window (fixed size)
medium 18 minA fixed sliding window looks at every run of exactly k neighbouring items.
Video lesson · Chapter 1 of 8
Three minute signal
Fixed window
1:07Reel
How it works
Step through the idea, or press Play.
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 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 items has such windows.
What this topic builds on
Two pointers
The window is two indexes,
LandR, 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.
- 1Enter
nums[i]joins at the right edge - 2Leave
nums[i - k]drops off the left edge - 3RecordUpdate the answer for the window
i - k + 1toi
The window always holds exactly $k$ items: one in, one out, every step.
Brute force
Re-adding the same numbers: O(n · k)
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: 250500How many reads brute force makes
The trick
Add one, drop one
The sliding update
window += nums[i] - nums[i - k].The fixed-window loop
Sliding over [2, 1, 5, 1, 3, 2] with k = 3
| i | Leaves | Enters | Window | Sum | best |
|---|---|---|---|---|---|
| 0 to 2 | – | 2, 1, 5 | [2, 1, 5] | 8 | 8 |
| 3 | 2 | 1 | [1, 5, 1] | 8 − 2 + 1 = 7 | 8 |
| 4 | 1 | 3 | [5, 1, 3] | 7 − 1 + 3 = 9 | 9 |
| 5 | 5 | 2 | [1, 3, 2] | 9 − 5 + 2 = 6 | 9 |
Cost
Why it is O(n) time and O(1) space
Reads made by the slide
window and best, so the extra space is .| n | k | Brute force reads | Sliding reads | Saving |
|---|---|---|---|---|
| 6 | 3 | 12 | 9 | 1.3× |
| 100 | 10 | 910 | 190 | 4.8× |
| 1,000 | 500 | 250,500 | 1,500 | 167× |
| 100,000 | 1,000 | 99,001,000 | 199,000 | 497× |
Template
Maximum sum and maximum average of k
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)) # 5Edge cases
The inputs that break careless code
| Input | k | Window sums | Answer | What it tests |
|---|---|---|---|---|
| [2, 1, 5, 1, 3, 2] | 3 | 8, 7, 9, 6 | 9 | The standard case: best in the middle |
| [4, 4, 4, 4, 4] | 2 | 8, 8, 8, 8 | 8 | Ties: > keeps the first best window |
| [1, 2, 3, 4, 5, 6] | 3 | 6, 9, 12, 15 | 15 | Best is the last window: loop to |
| [4, −1, 2, −3, 5, 1] | 3 | 5, −2, 4, 3 | 5 | Negatives: best is the first window, not 0 |
| [1, 3, 2, 5, 1, 2, 3, 4] | 4 | 11, 11, 10, 11, 10 | 11 | Large k: only windows |
| [3, 8, 1] | 4 | none | None | : no window fits |
Guarding the input
sum(nums[:k]) never raises: with it silently sums a short window. Check first.Do
- Loop the entering index over
range(k, len(nums)): that is slides. - Start
bestat the first window's sum. - Use the window that ends at
i: it spansi - k + 1toi. - Record an answer only once the window holds items (
i >= k - 1).
Don't
- Write
range(k, len(nums) - 1)and lose the last window. - Start
bestat 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
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")) # FalseSets and counters
Duplicates, distinct values and vowels
Duplicate within k
Keep a set of the last values. If the entering value is already in it, two equal values sit at most 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.
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)) # 3Window 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 . A heap works in 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 the maxima are [3, 3, 5, 5, 6, 7].
One step of the deque
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]<= to >= for the window minimum.Deque trace for [1, 3, −1, −3, 5, 3, 6, 7], k = 3
| i | x | Expired | Popped from back | Deque (index:value) | Output |
|---|---|---|---|---|---|
| 0 | 1 | – | – | 0:1 | – |
| 1 | 3 | – | 0:1 | 1:3 | – |
| 2 | −1 | – | – | 1:3, 2:−1 | 3 |
| 3 | −3 | – | – | 1:3, 2:−1, 3:−3 | 3 |
| 4 | 5 | 1:3 | 3:−3, 2:−1 | 4:5 | 5 |
| 5 | 3 | – | – | 4:5, 5:3 | 5 |
| 6 | 6 | – | 5:3, 4:5 | 6:6 | 6 |
| 7 | 7 | – | 6:6 | 7:7 | 7 |
Proof
Why the deque is O(n), and why it is correct
Amortised cost
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 . The deque never holds more than indexes: space.| Approach | Time | Space | Notes |
|---|---|---|---|
max() on every window | Fine for tiny , quadratic in the worst case | ||
| Max-heap with lazy deletes | Pop the top while its index is outside the window | ||
| Monotonic deque | The interview answer |
Pattern map
Fixed window, variable window, prefix sums or two pointers?
Choosing the technique
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 , 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
| Problem | Window state | Cost |
|---|---|---|
| 643 Maximum Average Subarray I | Running sum | , |
| 1343 Subarrays of size k with average at least a threshold | Running sum, count windows | , |
| 1456 Maximum vowels in a substring of length k | Vowel counter | , |
| 219 Contains Duplicate II | Set of the last k values | , |
| 438 Find All Anagrams / 567 Permutation in String | Letter counts | , |
| 2461 Max sum of distinct subarrays of length k | Running sum + counts | , |
| 1423 Max points from cards | Window of n − k on the middle (the complement) | , |
| 239 Sliding Window Maximum | Monotonic deque of indexes | , |
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.