Skip to the workspace
Pebellslearn by building
Sliding Window  ›  Lesson

Fixed Windows: Slide, Don't Recount

More Exercises 12 minA window of fixed size moving one step at a time gains exactly one item and loses exactly one, so its total can be updated with one addition and one subtraction instead of being recounted.

leetcode / Fixed Windows: Slide, Don't Recount

Explore each scene at your own pace.

01 · The rule

The rule

Fixed Windows: Slide, Don't Recount

A café counts customers each hour: 5, 1, 3, 8, 2 and 6. The owner wants the busiest three-hour stretch, to schedule an extra barista. You could add up every stretch of three from scratch. But neighbouring stretches share two of their three hours, and recounting shared hours is wasted work.

The rule

Add the one coming in, subtract the one going out.

A fixed window is a stretch of exactly k consecutive items that moves one step at a time. When it moves right, exactly one item enters on the right and exactly one leaves on the left. Everything in between is unchanged, so the new total is the old total plus the newcomer minus the leaver.

def best_k_total(nums, k):
    window = sum(nums[:k])              # the first window, added once
    best = window
    for i in range(k, len(nums)):
        window += nums[i] - nums[i - k] # in comes nums[i], out goes nums[i - k]
        best = max(best, window)
    return best

Recounting costs k additions per window, about n × k in total: for 100,000 hours and a window of 1,000 that is a hundred million additions. Sliding costs two operations per step, about n in total, whatever k is. The best average of k consecutive items comes for free, too: it is the best total divided by k, because k never changes.

The same move works for anything you can add and remove: a sum, a count of vowels, a dictionary of letter counts. It does not work directly for things you cannot "subtract", like the maximum of the window, because when the maximum leaves you do not know what the new one is.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.