Three problems on windows of one fixed width. The move: decide what the window state is, so that one value enters, one leaves and the update costs almost nothing.
You work on the back end of a ride-hailing app, an ad-serving system and a platform dashboard. The three problems on this street each look at every window of k values in a row. A window of k values moves one position at a time, so one value enters and one value leaves.
The work is in the state. It is what you keep about the current window so that a step costs almost nothing. Here is each problem's state.
| Problem | The window holds | The state | One step |
|---|---|---|---|
| Best k days on a repeating roster | k days, wrapping from the last day to the first | one total | add the entering day, drop the leaving day |
| Two quiet maintenance windows | two windows of k hours with a gap | every window's total, and the smallest earlier total | the newest allowed first window joins the minimum |
| Maximum of every window of k | k values | a deque of candidate positions | pop weaker values, add the new one, drop an expired front |
Read the last two columns together. The first problem keeps one number. The third keeps a structure, because its statistic cannot be undone.
Recomputing a window from scratch costs k steps. On a list of 200,000 values with k of 1,000, that is 199,001,000 additions. One pass with a state that updates in place makes about 200,000 steps.
Before you write a loop, answer one question. What do I keep about the window, so that adding one value and removing one value updates it in constant time?
After every step the state describes exactly the k values in the window: the entering value is added, the leaving value is removed, and nothing else is touched.
For a total the answer is a number, and the update is window += entering - leaving. The first window costs k steps once, and every later step costs one.
Exercise · Put it in order: Slide over a repeating roster. Arrange the lines to find the highest total of k days in a row on a roster that starts again after its last day.
def best_wrapped_total(trips, k):
n = len(trips)
window = sum(trips[:k])
best = window
for start in range(1, n):
window += trips[(start + k - 1) % n] - trips[start - 1]
best = max(best, window)
return best
window += trips[start + k - 1] - trips[start - 1]Slide a fixed window by adding the entering value and dropping the leaving one: the whole pass costs n steps, not n times k.
The Academy lesson Sliding window: fixed and variable windows slides a window and keeps a total. Monotonic deques and window extremes builds the deque. This street changes three things.
The window can wrap. A roster repeats, so a window may start on the last day and continue on the first. Start a window at every position and take the entering index modulo n. For the roster [5, 1, 1, 5] and k of 2, the best wrapped total is 10, while a loop that stops at the last full window finds only 6.
The state may not be undoable. A total loses exactly the leaving value. A maximum may be the leaving value, and then nothing tells you the next one.
Tracking only the entering maximum on [5, 1, 1, 1] with k of 2 gives peaks 5, 5, 5, where the true peaks are 5, 1, 1. The deque holds the candidates, and the front is dropped when its position is i - k or older.
The state can summarise earlier windows. The two maintenance windows must not overlap and must leave a gap. Compute every window's total in one pass, then slide a second index that trails the first by the width plus the gap, and keep the smallest total seen.
For 100,000 hours, k of 1,000 and no gap there are 4,802,147,001 pairs of windows, so the answer needs 64 bits. One pass visits 99,001 windows.
Exercise · Find the bug: The front that never expires. This sums the peak of every window of k values. A deque keeps the candidate positions. It is right on most inputs, but one line lets a position that left the window stay in front.
from collections import deque
def window_max_total(counts, k):
queue = deque()
total = 0
for i, value in enumerate(counts):
while queue and counts[queue[-1]] <= value:
queue.pop()
queue.append(i)
if queue[0] < i - k:
queue.popleft()
if i >= k - 1:
total += counts[queue[0]]
return totalA maximum cannot be undone like a total. Tracking only the entering maximum never forgets the 5; a deque drops it when it expires.
Exercise · Break it: A roster that stops at the end. This finds the highest total of k days in a row on a roster that repeats after its last day. It slides the window from the first day to the last full window. Find an input where it gives the wrong answer.
def best_total(trips, k):
window = sum(trips[:k])
best = window
for start in range(1, len(trips) - k + 1):
window += trips[start + k - 1] - trips[start - 1]
best = max(best, window)
return bestSolve them in this order. The first keeps one total and adds a wrap. The second keeps a summary of earlier windows. The third keeps a deque, because its statistic cannot be undone.
Before you code each problem, write the state in one line, and then the update for one entering and one leaving value. If the update needs more than constant time, the state is wrong.
Give each problem about 25 minutes. Spend the first five on the state line. Then walk six values by hand with a window of 2 or 3, writing the state after every step.
Three cases come back on every rung. The window may equal the whole list, the window may be one value wide, and the first window needs its own setup. Write one small test for each.
When a solution fails, rebuild the state for the failing window from scratch and compare it with the state you kept. The first step where they differ is the bug.
i - k.n. The state can also summarise earlier windows.Checkpoint · Fixed windows
Q1/5 What should you decide first on every problem of this street?
Answer: B
The width is given. The state decides whether a step costs almost nothing, and so whether the whole pass costs n steps instead of n times k.
Q2/5 The roster is 5, 1, 1, 5 and repeats after its last day. What is the highest total of 2 days in a row?
Answer: B
The last day and the first day are neighbours on a repeating roster, so the window 5 and 5 is allowed. A loop that stops at the last full window finds only 6.
Q3/5 A window slides one step. Which statistic can be updated by removing only the leaving value?
Answer: B
A total loses exactly the leaving value. A maximum may be the leaving value, and then the next largest is unknown, so it needs a deque of candidates.
Q4/5 The deque holds positions of candidates. At index 5 the window is 3 values wide. Which front positions have left the window?
Answer: C
The window at index 5 holds positions 3, 4 and 5. So position 2, which is i - k, has left, and the check must use at most, not below.
Q5/5 A list has 200,000 values and k is 1,000. About how many additions does it take to recompute the total of every window from scratch?
Answer: C
There are 199,001 windows of 1,000 values each, which is 199,001,000 additions. A running total makes about 200,000.
Review cards from this lesson.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.