Lesson 4 of 4
Windows that grow and shrink
When the question asks for the longest or shortest block that obeys a rule, one window answers it in one pass. The right edge moves every step, and the left edge catches up only when the rule forces it.
Explain why the left edge of a variable window never has to move back
Write the template for a longest answer (record after shrinking) and for a shortest answer (record before each shrink)
Choose the notebook a rule needs, such as a set, a running sum, letter counts or a missing counter
Explain why a while loop inside a for loop still costs O(n) here
Recognize when a window fails, such as sums with negative numbers
In the last lesson the window had a size you were given, such as the best total over 3 days in a row. Often the size is the answer itself. Two questions of that kind:
- In the string
"abcbde", how long is the longest stretch with no repeated character? - In daily sales
[2, 1, 4, 3, 1, 5], what is the fewest days in a row whose sales add up to at least 8?
You could try every block. Six items have 21 blocks (6 of length 1, 5 of length 2, and so on down to 1 of length 6), and n items have about n2/2, so trying them all costs O(n2) or more. When n is 100,000, that is about 5 billion blocks.
This lesson answers both questions in one pass with a window that grows on the right and shrinks on the left. The same few lines then solve four classic problems, the last of them a hard one.
The longest stretch without a repeat
A substring is a block of consecutive characters: "cbd" is a substring of "abcbde", but "acd" is not. We want the longest substring with no character in it twice.
Brute force first: the direct method that tries every candidate. Start at each position, read to the right, and stop at the first repeat. Here is every walk on "abcbde":
| Start | Reads | Stops because | Length |
|---|---|---|---|
| 0 | a, b, c, b | the second b repeats | 3 |
| 1 | b, c, b | the second b repeats | 2 |
| 2 | c, b, d, e | the text ends | 4 |
| 3 | b, d, e | the text ends | 3 |
| 4 | d, e | the text ends | 2 |
| 5 | e | the text ends | 1 |
The best is 4, from start 2: "cbde". That took 17 reads for 6 characters, and most of the reads repeat earlier ones: the walk from start 1 reads b and c again and stops at the same b as the walk from start 0.
The walk from start 0 tells us more than its length. It stopped because positions 1 and 3 both hold b. Any walk that starts at 0 or 1 and reaches position 3 holds both b's, so it has to stop by position 2, and the best of those walks, "abc", is already counted. Starts 0 and 1 are finished. The next start worth trying is 2, right after the first b, and we already know that c and the second b fit together. Nothing needs to be read again.
As in the last lesson, a window is a block of consecutive positions from index left to index right, both included. In Python it is s[left:right + 1] (a slice stops before its end index, so we add 1), and its length is right - left + 1. What we did by hand is a variable window: a window whose size changes as it walks. The rule is what every window we keep must obey; here it is "no character twice". Move right one character at a time. When the new character is already inside, move left forward until the old copy is gone. left never moves back, because every start it passes is stuck behind a repeat.
The widget runs this on "abcbde". The cells are the characters and the bracket marks the window. The readouts show the characters inside it, kept in a set (module 3: a collection with no repeats, where asking "is this character inside?" takes one step on average), the best length so far, and how many times the pointers have moved. Before you press Next, guess how many times left moves.
Try the same moves by hand on a new string.
Run the same moves by hand on "xyzzy": right reads one character per step, and when that character is already in the window, left moves forward until the old copy is gone. In all, how many times does left move? Type a whole number.
Type a number: 12, -1, 0.5 and 3/4 all work. Enter checks.
The template in code
How do the widget's moves look in Python? They fit in a few lines. The notebook, the values the walk keeps up to date, is a set named window that holds the characters of s[left:right + 1], plus left and best. enumerate(s) hands out each position with its character, so ch is always s[right]. Before you step through, guess what the function returns for "abba", and at which value of right the window has to shrink.
def longest_unique(s):window = set()left = 0best = 0for right, ch in enumerate(s):while ch in window:window.remove(s[left])left += 1window.add(ch)best = max(best, right - left + 1)return best
(nothing printed yet)Every pass makes the same three moves. This is the template for every problem in this lesson:
- Grow.
rightmoves one step, and the new item is about to join the notebook. - Shrink while the window breaks the rule. Drop
s[left]from the notebook and moveleftforward. Here the rule is "no character twice", and the check comes beforechjoins: a set cannot hold two copies, so the test is "wouldchrepeat?" - Record. The window obeys the rule again, so its length is a candidate for
best.
The three moves keep one promise, a fact that is true after every pass:
Why it holds: left passes a start only when the block from that start to right breaks the rule, and every longer block from the same start contains that block, so it breaks the rule too. So a start that left has passed can never begin a good window again. Every substring ends at some right, and we record the longest good one there, so when the walk ends best is the answer.
Check the promise on a new string: print the window after every pass.
This is the template's loop with a print where the record line was, so it prints the window s[left:right + 1] after each pass. Type exactly what it prints, one window per line.
s = "aabcb"
window = set()
left = 0
for right, ch in enumerate(s):
while ch in window:
window.remove(s[left])
left += 1
window.add(ch)
print(s[left:right + 1])
Two loops, still one pass
The while loop sits inside the for loop, and nested loops often mean O(n2). Here, count pointer moves instead of loop levels. right moves n times. left moves one step per pass of the inner loop, only forward, and it can never go past the end of the string, so over the whole walk it moves at most n times. Each move adds or removes one character from a set, O(1) on average. So the total is at most 2n moves: O(n) time. The widget counted 8 moves for 6 characters.
Here is the same template with a different rule, a budget, and a running sum as the notebook.
Each day has a positive cost, and you have a budget. Put the lines in order to build longest_within(costs, budget), which returns the most days in a row whose total cost is at most budget (0 if no single day fits). Indentation is part of each line. Three lines do not belong.
Add lines from the list below, in order.
total += costtotal -= costs[left]left += 1best = max(best, total)while total >= budget:left, total, best = 0, 0, 0def longest_within(costs, budget):for right, cost in enumerate(costs):return right - left + 1while total > budget:best = max(best, right - left + 1)return best
Now write the repeat-free window from a blank editor. The tests include "abba" and a string with no repeats at all.
A dict works as the notebook too. Map each character to the last position where you saw it, and when ch has been seen before, left can jump past the old copy in one step:
def longest_unique(s):
last = {} # character -> the last position it was seen
left = 0
best = 0
for right, ch in enumerate(s):
if ch in last:
left = max(left, last[ch] + 1) # jump past the old copy, never back
last[ch] = right
best = max(best, right - left + 1)
return best
Keep the max. The dict never forgets, so it can point at a copy that is already outside the window. On "abba", when the last a arrives, left is 2 and the old a sits at 0. Without the max, left would jump back from 2 to 1 and count "bba", which repeats b, for a wrong answer of 3.
Shortest instead of longest
Back to the sales: [2, 1, 4, 3, 1, 5], and the fewest days in a row adding up to at least 8. Every number is positive, and that gives the window two clean moves: adding a day raises the sum, and dropping one lowers it.
Turn the template around. Now we want the shortest window that reaches 8. Grow on the right until the sum reaches 8. That window is a candidate, so record its length first, then drop from the left to try a shorter one, and repeat while the sum is still at least 8. When the loop stops, the sum is below 8: that is the rule this window keeps after every inner loop. The only change from the longest version is where the recording happens.
The widget shows the sum inside the bracket and the shortest length so far. Before you press Next, find the answer by eye: the fewest days in a row that add up to at least 8.
In code, the record moves inside the while loop. The trace runs it on a shorter list, [1, 2, 6, 1] with target 7. Before you step through, guess how many times best changes after its first value.
def shortest_subarray(nums, target):left = 0window_sum = 0best = len(nums) + 1for right, x in enumerate(nums):window_sum += xwhile window_sum >= target:best = min(best, right - left + 1)window_sum -= nums[left]left += 1return best if best <= len(nums) else 0
(nothing printed yet)best = len(nums) + 1 means "none found yet", because no block is that long. The last line, return best if best <= len(nums) else 0, reads the way it sounds: return best if it is a real length, else 0.
When the walk ends, the promise gives the answer. The last window is below the target, and every block that starts at left or later sits inside it, so with positive numbers none of those qualifies. Every start is covered.
shortest_subarray from the trace above assumes positive numbers. What does it return for shortest_subarray([1, -2, 5], 4)?
Choose one answer, then check.
Here is the full problem. "At least" means >=.
A notebook of counts
The next problem (LeetCode 424) gives you a string of capital letters and lets you change at most k of them. What is the longest block you can make all one letter?
First, what one block needs. Take "AABA". The cheapest plan keeps the most common letter, A with 3 copies, and changes the rest: 1 letter. So a block needs its length minus the count of its most common letter in changes. With k = 1, "AABA" is good (4 − 3 = 1) and "AABAB" is not (5 − 3 = 2).
That rule fits the template. The notebook is counts, a dict from each letter to its number of copies in the window; counts.get(ch, 0) reads a count, or 0 for a letter not seen yet. The shrink loop runs while the length minus max(counts.values()), the largest count, is above k. Before you step through, guess the answer for "AABAB" with k = 1.
def longest_after_changes(s, k):counts = {}left = 0best = 0for right, ch in enumerate(s):counts[ch] = counts.get(ch, 0) + 1while (right - left + 1) - max(counts.values()) > k:counts[s[left]] -= 1left += 1best = max(best, right - left + 1)return best
(nothing printed yet)Why recompute the maximum instead of keeping it in one variable? When a letter leaves, the top count can drop, or another letter can take the lead, as B did here. max(counts.values()) looks at no more than 26 counts, a fixed cost, so the walk stays O(n).
Practice counts with a different rule first: at most two different characters.
Write longest_two_kinds(s), which returns the length of the longest substring of s that uses at most two different characters. Use the template with a dict of counts: counts[c] is how many times c appears in the window. Then press Watch it run to see the dict grow and shrink.
raise NotImplementedError, then press Run tests. Each check says what it expects.Now the changes problem itself.
Covering a set of letters
The capstone, LeetCode 76, is a hard problem. A substring of text covers letters if it holds every character of letters at least as many times as letters does. To cover "AAB" it needs two A's and one B, and other characters may sit inside too. We want the shortest substring that covers.
Covering behaves like a sum of positive numbers: adding a character never breaks a cover, and dropping one never creates a cover. So this is the shortest version of the template: grow until the window covers, then record and shrink while it still covers.
The hard part is the notebook. LeetCode's strings hold upper and lower case letters, 52 kinds, so comparing every count at every step means up to 52 checks each time, and more code to get right. Two names do the job:
need[c]: how many more copies ofcthe window needs. It starts as the count ofcinlettersand goes below 0 when the window holds extras.missing: how many characters are still needed, counting repeats. The window covers exactly whenmissingis 0.
When ch enters, if need[ch] was above 0, this copy fills a real gap, so missing drops by 1; either way need[ch] drops by 1. When text[left] leaves, its need rises by 1, and if that makes it above 0, a needed copy has gone, so missing rises by 1.
Counter(letters) (module 3) counts each character of letters, and a Counter answers 0 for a key it does not hold, so need["B"] is 0 even though letters has no B. Before you step through, guess the answer for "BAAC" with letters "AC".
from collections import Counterdef min_window(text, letters):need = Counter(letters)missing = len(letters)left = 0best_start, best_len = 0, len(text) + 1for right, ch in enumerate(text):if need[ch] > 0:missing -= 1need[ch] -= 1while missing == 0:if right - left + 1 < best_len:best_start, best_len = left, right - left + 1leaving = text[left]need[leaving] += 1if need[leaving] > 0:missing += 1left += 1if best_len > len(text):return ""return text[best_start:best_start + best_len]
(nothing printed yet)Work one by hand before the full problem.
Find the shortest substring of "ADBA" that covers "AB", by hand. On paper, track need, missing and left as each character enters, the way the trace did. Reveal one step at a time and check yourself.
Work it on real paper: writing each step is the point. Then check your final answer here and compare your working with the walk-through.
Type a number: 12, -1, 0.5 and 3/4 all work. Enter checks.
This is the only hard problem in the module, with a target time of 40 minutes. If you are still stuck after about 30 minutes of real effort, read the approach, then re-solve it from a blank editor on another day.
Four problems, one template. They differ in the rule, the notebook and where the record happens:
| Problem | Rule the window keeps | Notebook | When to record |
|---|---|---|---|
| Longest without a repeat | no character twice | a set | after the shrink loop |
| Longest after k changes | length minus top count is at most k | letter counts | after the shrink loop |
| Shortest reaching a target | sum below the target | a running sum | inside the loop, before each shrink |
| Shortest covering letters | does not cover yet | need and missing | inside the loop, before each shrink |
A window fits when the answer is one block and growing it can only break the rule, so shrinking is the one repair. Try that test on four new questions.
Which of these can a variable window answer in one pass? Choose every one that fits.
Choose every option that applies, then check.
Last, say it the way you would in the room.
An interviewer asks for the most days in a row whose total cost stays at most a budget (every cost is positive). Before typing, say the walk, the notebook, the promise and the cost. Then answer the follow-up: "Your while loop is inside a for loop. Isn't that O(n2)?"
Saved in this browser as you type.