BeginnerSliding Window

Fixed-size windows: add one, drop one

Summing every window of size k? Don't re-add k numbers each time: add the one entering and subtract the one leaving.

The idea

Neighbouring windows share all but two elements. Re-summing each window costs O(k) per window, O(n·k) in total. Instead keep a and update it in as the window slides.

Worked example

Max average of size-3 windows in [1, 12, -5, -6, 50, 3]

  1. First window 1 + 12 − 5 = 8
  2. Slide: + (−6) − 1 = 1
  3. Slide: + 50 − 12 = 39
  4. Slide: + 3 − (−5) = 47 → best sum 47, average 47/3

Pseudocode

The steps in plain words. ← means “set to”; indentation shows what's inside what.

window ← sum of the first k numbers
best ← window
for right from k to the end:
window ← window + nums[right] − nums[right − k](one in, one out)
best ← max(best, window)
return best

See it run

The worked example, step by step, beside the Python. The highlighted line is the one running.

Step-by-step

nums = [2, 1, 5, 1, 3, 2], k = 3

02
11
25
31
43
52
window = 8best = 8

Solution · Pythonline 2

def max_average(nums, k):
window = sum(nums[:k])
best = window
for i in range(k, len(nums)):
window += nums[i] - nums[i - k]
best = max(best, window)
return best / k

Step 1 of 5· line 2

Add up the first window once: 2 + 1 + 5 = 8.

  • inside the window

time, O(1) space.

How to spot it

  • “every of length k”, “window of size k”.

Common mistakes

  • Subtracting nums[i - k + 1] instead of nums[i - k] (off by one).
  • Starting best at 0 when sums can be negative.

Practise the ideas first

Practise it

Go further