Sliding window (fixed size)
medium 18 minA fixed sliding window looks at every run of exactly k neighbouring items.
See it run
Keep a window of exactly k items and move it one step at a time: add the item that enters, drop the item that leaves, and never re-read the middle.
Operations
brute force
Sum every window of k from scratch with a nested loop, re-reading the k − 1 numbers each window shares with the last.
Step 1 of 6
Best sum of 3 in a row
brute force, k = 3
- 20
- 11
- 52
- 13
- 34
- 25
nums = [2, 1, 5, 1, 3, 2], k = 3. There are n - k + 1 = 4 windows. Brute force sums each one from scratch with an inner loop.
Step 1: Best sum of 3 in a row
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): # re-read all k numbers total += nums[j] reads += 1 best = max(best, total) return best, readsprint(max_sum_brute([2, 1, 5, 1, 3, 2], 3)) # (9, 12)- Time
- O(n · k)
- Space
- O(1)
- reads
- (n − k + 1) · k
- sliding window
- O(n)
Write it first in an interview to show you understand the question, then point at the repeated reads: that waste is exactly what the slide removes.
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Re-summing every window
criticalsum(nums[i:i + k]) inside the loop reads k numbers per window, so the whole thing is O(n · k). It looks like one loop but it is the brute force. Keep one running sum.
Wrongbest = float("-inf")for i in range(len(nums) - k + 1): best = max(best, sum(nums[i:i + k])) # k reads each timeRightwindow = sum(nums[:k])best = windowfor i in range(k, len(nums)): window += nums[i] - nums[i - k] # 2 reads each time best = max(best, window)Starting best at 0
majorIf every window sums to a negative number, best = 0 is returned even though no window has sum 0. Start from the first window's sum (or minus infinity).
Wrongbest = 0window = sum(nums[:k])# [-3, -1, -2], k = 2 returns 0Rightwindow = sum(nums[:k])best = window# [-3, -1, -2], k = 2 returns -3Off by one in the loop range
majorThe entering index i runs from k to n − 1 inclusive, which is range(k, n). range(k, n - 1) skips the last window, and on a rising list that is exactly the best one.
Wrongfor i in range(k, len(nums) - 1): # misses the last window window += nums[i] - nums[i - k]Rightfor i in range(k, len(nums)): # i = k .. n - 1 window += nums[i] - nums[i - k]Leaving zero counts in the dict
major{'a': 1, 'b': 0} is not equal to {'a': 1}, so a window that is a real anagram fails the comparison. Delete a key when its count drops to 0.
Wronghave[old] -= 1if have == need: # {'b': 0} breaks equality out.append(i - k + 1)Righthave[old] -= 1if have[old] == 0: del have[old]if have == need: out.append(i - k + 1)Storing values in the max deque
majorWith values alone you cannot tell whether the front has left the window, and equal values become ambiguous. Store indexes and read nums[dq[0]].
Wrongdq.append(x)if dq[0] == nums[i - k]: # wrong when values repeat dq.popleft()Rightdq.append(i)if dq[0] <= i - k: # index tells you it expired dq.popleft()Recording before the window is full
minorFor i < k − 1 the window has fewer than k items. Recording then adds extra, wrong answers to the front of the output.
Wrongfor i, x in enumerate(nums): ... out.append(nums[dq[0]]) # also for i = 0, 1Rightfor i, x in enumerate(nums): ... if i >= k - 1: out.append(nums[dq[0]]) # n - k + 1 answers
Interview tips
How to explain it
- Start from brute force: n − k + 1 windows, k reads each, O(n · k).
- Then the key line: neighbouring windows share k − 1 items, so only the two ends change.
- Name the state you keep (a sum, a count map, a deque) and what add and drop do to it.
- Finish with O(n) time and the space of that state: O(1), O(alphabet) or O(k).
When to reach for it
- Subarray or substring of an exact length k: sum, average, count, distinct, vowels.
- Anagram or permutation of a pattern inside a longer string: a count map of size len(p).
- Maximum or minimum of every window: a monotonic deque of indexes.
- Duplicates within distance k: a set holding the last k items.
Memory tricks
- S-A-U: Subtract the leaving item, Add the entering item, Update the best.
- A train window: the frame stays the same size, one scene leaves as one enters.
- The magic line: window += nums[i] - nums[i - k].
- Deque rule: a newcomer evicts every smaller, older value behind it.
Consider something else when
- The window size is not given and depends on a condition: variable sliding window.
- You need sums of many arbitrary ranges, not one sweep: prefix sums.
- The items need not be contiguous (subsequences): DP or two pointers on sorted data.
- You need the median of every window: two heaps or a sorted list, not a deque.