Android & iPhone apps are coming soon. Log in for a plan and reminders made for you β†’

Know this before you start: β€œFixed-size windows (every window of size k)”

Fixed-size sliding windows

To look at every block of k items, don't recompute each one: slide by one, add the item coming in and remove the one going out.

The idea

A window is a range [left, right] of the array. With a fixed size k, moving it one step changes only two items: one enters on the right, one leaves on the left.

Keep whatever you're measuring (a sum, a count) for the current window and update it with just those two items. That makes each step O(1) instead of O(k).

See it step by step

Largest sum of 3 consecutive numbers in [2, 1, 5, 1, 3, 2]

  1. First window [2, 1, 5] β†’ 8
  2. Slide: +1 βˆ’2 β†’ 7. Slide: +3 βˆ’1 β†’ 9. Slide: +2 βˆ’5 β†’ 6
  3. Best: 9 (the window [5, 1, 3]).

In code (Python)

def max_window_sum(nums, k):
    window = sum(nums[:k])
    best = window
    for right in range(k, len(nums)):
        window += nums[right] - nums[right - k]   # in, out
        best = max(best, window)
    return best

print(max_window_sum([2, 1, 5, 1, 3, 2], 3))   # 9

O(n) time, O(1) space.

When you'll use it

  • β€œEvery subarray / substring of length k”, averages over k, counts inside a block of k.

Common mistakes

  • Removing nums[right βˆ’ k + 1] instead of nums[right βˆ’ k].
  • Starting `best` at 0 when sums can be negative.

Practise it: Sliding Window

Go further