Algorithms · Sliding window

The sliding window

Find the biggest total of k numbers in a row.

The problem

Return the biggest total of k numbers that sit next to each other in nums. (LeetCode asks for the average; it’s the same idea.)

best_window([1, 12, -5, -6, 50, 3], 4)51
best_window([5], 1)5
Sliding window. Update, don’t recount. A train window: one tree leaves on the left as another arrives on the right.

Start with the way that works

This version is correct. It is also the slow one. Read it first: the fast way is easier to find once you can see what the slow way wastes.

def best_window(nums, k):take the numbers and the window size k
best = Noneno best yet
for start in range(len(nums) - k + 1):try every starting position
total = 0add up this window from scratch
for x in nums[start:start + k]:each number inside the window
total += xadd it
if best is None or total > best:the best so far?
best = totalremember it
return bestthe biggest window total

Now ask: what if there were a billion?

“How many requests did this customer make in the last minute?” is a sliding window. Stripe’s rate limiter answers it millions of times a second by updating running counts, not recounting.

Aim for O(n)🌱 warm-up

Think it through

Two windows of k numbers, one step apart. How many numbers are different between them?

  • All k
  • Two: one leaves, one arrives
Show the answer

Two: one leaves, one arrives. Neighbouring windows share almost everything. So don’t add the window up again: take away the number that left and add the one that arrived.

So how long does each slide take?

  • k steps
  • One step
Show the answer

One step. Update, don’t recount. That turns n × k into n. It’s how rolling averages, rate limiters and live dashboards keep up.

Stuck? 3 nudges, smallest first
  1. Two windows next to each other share almost all their numbers. Why add them all up again?
  2. When the window slides one step right, exactly one number enters and one number leaves.
  3. Add up the first k numbers once. Then for each new i: total += nums[i] - nums[i - k], and keep the best.

The fast way

Try it yourself before you open this. The slow version above already passes every test, so you can change it one step at a time.

Show the fast version
def best_window(nums, k):take the numbers and the window size k
total = sum(nums[:k])add up the first window once
best = totalit's the best so far
for i in range(k, len(nums)):slide the window one step right
total += nums[i] - nums[i - k]one number comes in, one goes out
best = max(best, total)keep the biggest
return bestthe biggest window total

Where it’s used for real

Solve it yourself.

It runs right in the page: the tests, the gremlins that try to break it, and a race up to a billion. Free, nothing to install.

More with sliding window