Four problems whose window answer depends on counts. The move: keep a summary beside the counts, so that each count that changes updates the answer in constant time.
You work on the back end of a social feed and an online store. The problems on this street look at windows, and in each the answer depends on how many items of a kind the window holds.
In one problem the kind is a topic, and the answer is the largest count of any topic. In another, the kind is a ready bin, and the answer is how many ready bins fit inside a block. The last two count categories and services, and the answer is whether every one of them is present.
| Problem | The window | The counts | The summary read each step |
|---|---|---|---|
| Total heat of every window of k posts | k posts | posts per topic | the peak: the largest count |
| Fewest swaps to group the ready bins | as wide as the number of ready bins | ready bins in the window | the number of ready bins inside |
| Shortest stretch of a looping carousel that shows every category | a stretch of a loop, read twice | items per category | the number of categories still missing |
| Shortest cover of every service | a stretch of positions | positions per service, as one position holds several | the number of services still missing |
Read the last column. A window of counts is a table, but the answer is one number. If you rebuild that number at every step, you rescan the table.
On 100,000 posts with k of 1,000, rescanning costs 99,001,000 steps. Keeping the summary costs about 100,000.
Exercise · Break it: The block that must start at the left. This finds the fewest swaps to put all ready bins in one block. It counts the empty bins in the first stretch as wide as the ready bins. Find an input where it gives the wrong answer.
def fewest_swaps(bins):
width = sum(bins)
return width - sum(bins[:width])The move has two parts. First, name the one number the answer needs. Second, keep it in a variable next to the counts, and update it for each count that changes.
Beside the table of counts, keep the one summary the answer reads, and update it in constant time each time a count goes up or down.
A summary that only rises is easy. The number of ready bins in a window rises and falls by one, so it is a plain sliding total. The peak is harder, because it must fall when its topic leaves.
For the peak, keep a second table: how many topics hold each count. When a topic leaves with a count equal to the peak, and no other topic holds that count, the peak falls by one. Otherwise it stays.
Exercise · Predict the output: Total heat of three-post windows. The code keeps the count of each topic and a table of how many topics hold each count. At each full window it adds the peak. What does it print?
topics = [1, 2, 1, 3, 1]
k = 3
counts = {}
holders = [0] * (k + 2)
peak = 0
total = 0
for right in range(len(topics)):
c = counts.get(topics[right], 0)
counts[topics[right]] = c + 1
holders[c] -= 1
holders[c + 1] += 1
peak = max(peak, c + 1)
if right >= k - 1:
total += peak
leaving = topics[right - k + 1]
c = counts[leaving]
counts[leaving] = c - 1
holders[c] -= 1
holders[c - 1] += 1
if c == peak and holders[c] == 0:
peak -= 1
print(total)Keep the peak beside the counts: it rises when a count rises, and falls only when the leaving topic held it alone.
The Academy lesson Windows with counts keeps a table of counts and compares it with a pattern. Sliding window: fixed and variable windows slides a total, and Minimum covering window tracks how many required kinds are still missing. This street changes two things.
The summary must also fall. A cover question keeps a count of kinds still missing, and each count moves it by at most one. The peak is the same idea with a harder rule. Never lowering it is wrong.
On the topics 7, 7, 1, 2, 3 with k of 2, the true heats are 2, 1, 1 and 1, a total of 5. A peak that never falls gives 8.
The width can depend on the data. To group the ready bins, the block must be as wide as the number of ready bins, so you count them first. Then the window is a plain sliding total, and each empty bin inside the best window needs one swap with a ready bin outside it. For 1, 0, 1, 0, 1 the width is 3, the best window holds 2, and one swap is enough.
One more rule decides the peak's fall: the leaving topic must have held the peak, and no other topic may still hold it. Lowering the peak whenever the leaving count equals it is a bug that passes many inputs.
Exercise · Find the bug: The peak that falls too early. This sums the heat of every window of k posts, where heat is the largest count of one topic. It is right on most inputs, but one condition lowers the peak when it should not.
def total_heat(topics, k):
counts = {}
holders = [0] * (k + 2)
peak = 0
total = 0
for right in range(len(topics)):
c = counts.get(topics[right], 0)
counts[topics[right]] = c + 1
holders[c] -= 1
holders[c + 1] += 1
peak = max(peak, c + 1)
if right >= k - 1:
total += peak
leaving = topics[right - k + 1]
c = counts[leaving]
counts[leaving] = c - 1
holders[c] -= 1
holders[c - 1] += 1
if c == peak:
peak -= 1
return totalA peak that never falls overcounts: on 7, 7, 1, 2, 3 with k of 2 it gives a total of 8 where the answer is 5.
Solve them in this order. The first uses a plain sliding total whose width comes from the data. The second keeps a summary that must fall as well as rise. The last two cover a set: one on a loop, one where a position holds several items.
Before you code each problem, write the one number the answer reads, and say how one entering and one leaving item change it. If a change can move it in a way you cannot undo in constant time, the summary needs a second table.
Give each problem about 25 to 35 minutes. Spend the first five on the one number and its update. Then walk five or six values by hand, writing the counts and the summary at every step.
Three cases come back on every rung. The window may be as wide as the whole list, the window may be empty, and all items may be of one kind. Write one small test for each.
When a solution fails, rebuild the counts for the failing window from scratch and compare them with yours. Then compare the summary. The first difference tells you which update was wrong.
Checkpoint · Counts and cover
Q1/5 What does the move on this street ask you to keep beside the table of counts?
Answer: B
Rebuilding the summary from the table at every step costs a scan of the table. Keeping it beside the table makes the answer a read.
Q2/5 The topics in a window have counts 3, 2 and 2. The topic with count 3 leaves, so its count becomes 2. What happens to the peak?
Answer: B
The peak falls by one only when the leaving topic held it and no other topic holds that count. Here the table of holders for count 3 becomes empty, so the peak is 2.
Q3/5 The topics in a window have counts 2 and 2. A topic with count 2 leaves, so its count becomes 1. What happens to the peak?
Answer: A
The table of holders for count 2 still has one topic. A rule that lowers the peak whenever the leaving count equals it gives the wrong answer here.
Q4/5 A row of bins holds 4 ready bins. How wide is the window you slide to group them with the fewest swaps?
Answer: C
The final block holds all the ready bins, so it is as wide as their number. The window is found from the data first, and then it is slid like any fixed window.
Q5/5 The best window of width 3 already holds 2 ready bins. How many swaps does it take to group them?
Answer: B
Each empty bin inside the window needs one swap with a ready bin outside it. The width is 3 and 2 are inside, so one swap is enough.
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.