AlgoViz

Sliding window (fixed size)

medium 18 min

A 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

  1. 20
  2. 11
  3. 52
  4. 13
  5. 34
  6. 25
reads = 0best = −∞

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

    critical

    sum(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.

    Wrong
    best = float("-inf")for i in range(len(nums) - k + 1):    best = max(best, sum(nums[i:i + k]))   # k reads each time
    Right
    window = 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

    major

    If 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).

    Wrong
    best = 0window = sum(nums[:k])# [-3, -1, -2], k = 2 returns 0
    Right
    window = sum(nums[:k])best = window# [-3, -1, -2], k = 2 returns -3
  • Off by one in the loop range

    major

    The 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.

    Wrong
    for i in range(k, len(nums) - 1):    # misses the last window    window += nums[i] - nums[i - k]
    Right
    for 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.

    Wrong
    have[old] -= 1if have == need:          # {'b': 0} breaks equality    out.append(i - k + 1)
    Right
    have[old] -= 1if have[old] == 0:    del have[old]if have == need:    out.append(i - k + 1)
  • Storing values in the max deque

    major

    With values alone you cannot tell whether the front has left the window, and equal values become ambiguous. Store indexes and read nums[dq[0]].

    Wrong
    dq.append(x)if dq[0] == nums[i - k]:   # wrong when values repeat    dq.popleft()
    Right
    dq.append(i)if dq[0] <= i - k:         # index tells you it expired    dq.popleft()
  • Recording before the window is full

    minor

    For i < k − 1 the window has fewer than k items. Recording then adds extra, wrong answers to the front of the output.

    Wrong
    for i, x in enumerate(nums):    ...    out.append(nums[dq[0]])          # also for i = 0, 1
    Right
    for 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.