Three problems about the longest or most stretches that obey a rule. The move: grow the right edge each step and shrink the left only while the window breaks the rule.
You work on the back end of a bank, a monitoring service and a payments app. The three problems on this street each ask about stretches of consecutive values that obey a rule. One asks for the longest stretch, and one asks how many stretches there are.
The width is not fixed, so the rule decides it. The window grows to the right, and it shrinks from the left whenever the rule breaks.
| Problem | The rule | The state | What you record |
|---|---|---|---|
| Longest run of one status in a settlement file | every entry has the same code | the left edge of the run | the length of each run, and how many reach the best |
| Longest uniform stretch of a log after k corrections | window size minus the top letter count is at most k | letter counts and the top count | the longest window |
| Transfer stretches with a small risk product | the product is below the limit | the product | right - left + 1 stretches at every step |
Testing every stretch means n times n plus one over two windows. For 100,000 values that is 5,000,050,000. The window method moves each edge at most 100,000 times.
Exercise · Predict the output: How long a stretch can k corrections make?. The window may hold at most k letters that differ from its most common letter. The code keeps the largest window it has seen. What does it print?
levels = "AABABBA"
k = 1
counts = {}
left = 0
top = 0
best = 0
for right in range(len(levels)):
ch = levels[right]
counts[ch] = counts.get(ch, 0) + 1
top = max(top, counts[ch])
while right - left + 1 - top > k:
counts[levels[left]] -= 1
left += 1
best = max(best, right - left + 1)
print(best)The move is a loop with one fixed shape. The right edge advances once per step, and the new value joins the state. Then, while the window breaks the rule, the left edge advances and its value leaves the state.
The right edge moves once per step, and the left edge moves only while the window breaks the rule. Dropping a left value never makes the rule harder, so no edge moves back.
That last clause is what makes the loop correct. If dropping a value could break a window that was fine, the shrinking would skip valid stretches.
Each edge moves at most n times, so the whole pass is at most 2n moves. Both edges keep their place between steps, which is why the cost does not multiply.
Exercise · Find the bug: The product that equals the limit. This counts the stretches of transfers whose product of risk factors is strictly below the limit. Every factor is at least 1. One comparison is wrong.
def count_small_products(factors, limit):
product = 1
left = 0
total = 0
for right in range(len(factors)):
product *= factors[right]
while product > limit and left <= right:
product //= factors[left]
left += 1
total += right - left + 1
return totalGrow the right edge, shrink the left while the product is not below the limit, and add right minus left plus one stretches at each step.
The Academy lessons Sliding window: fixed and variable windows, Windows with counts and At most K and exactly K teach the loop and its counts. This street changes four things.
You record a different thing. A longest-window problem keeps the maximum of right - left + 1. A counting problem adds it at every step, because every stretch that ends at right and starts at left or later obeys the rule. For the factors 10, 5, 2, 6 and a limit of 100 the window sizes are 1, 2, 2 and 3, and the answer is 8.
The left edge can jump. In a run of equal status codes the rule breaks at one entry, and the new run starts there. So left = right in one move, with no shrinking step by step. For 1, 1, 2, 2, 2, 3 the longest run is 3, and one run reaches it.
A stale state can still be right. In the log problem the top count is never lowered when a letter leaves. The window only passes its best size when the top count rises, so a stale top cannot hide a longer answer. A comparison with a brute-force search on 500 random strings found no difference.
The rule must get easier when the left moves. With negative entries it does not. For -3, 4, -3 and a longest stretch with a sum of at most 0, the window method finds a length of 1. The whole list has a sum of -2 and a length of 3.
One more case: a single factor can break the rule alone, so the window becomes empty. Add 0 for that step, and let left pass right.
The shrinking window needs a rule that gets easier when a left value is dropped. With negative entries a sum does not.
Exercise · Break it: The last run. This finds the longest run of equal status codes and how many runs have that length. It closes a run when the code changes. Find an input where it gives the wrong answer.
def longest_status_run(statuses):
n = len(statuses)
left = 0
best = 0
count = 0
for right in range(1, n):
if statuses[right] != statuses[left]:
length = right - left
if length > best:
best = length
count = 1
elif length == best:
count += 1
left = right
return [best, count]Solve them in this order. The first jumps the left edge, the second keeps a count that may go stale, and the third counts every stretch instead of the longest.
Before you code each problem, write the rule as a test on the state, and say what dropping a left value does to it. If it can make the test harder, the window method does not apply.
Give each problem about 25 minutes. Spend the first five on the rule and the state. Then walk six or seven values by hand, writing left, right and the state at every step.
Three cases come back on every rung. One value may break the rule alone, the whole list may obey it, and the rule may hold with equality. Write one small test for each.
When a solution fails, check the edges first. A left edge that moves on a step where the rule held, or stays on a step where it broke, causes most wrong answers here.
right - left + 1, or the sum of right - left + 1 over all steps.Checkpoint · Variable windows
Q1/5 In the loop of this street, when does the left edge advance?
Answer: B
The right edge advances once per step. The left edge advances only to repair a broken window, and it never moves back.
Q2/5 You count the stretches whose product is below a limit. After a step the window holds 3 values and obeys the rule. How many stretches does that step add to the count?
Answer: C
Every stretch that ends at the right edge and starts at the left edge or later obeys the rule, because dropping values only lowers the product. That is right - left + 1, which is 3.
Q3/5 Which rule can the shrinking window not handle?
Answer: C
With negative entries, dropping a left value can raise the sum, so the rule does not get easier. For -3, 4, -3 and a limit of 0 the window method finds length 1, but the whole list is valid.
Q4/5 In the run problem, the status code changes at the right edge. Where does the left edge go?
Answer: B
Every entry of the old run is now outside the new run, so there is nothing to drop one at a time. The left edge jumps to the right edge.
Q5/5 In the log problem, the top letter count is not lowered when a letter leaves. Why is the answer still right?
Answer: B
A stale top is at least the true top, so the window stays at its best size instead of shrinking. It grows only when a letter count really reaches a new top, so the best size is still exact.
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.