Windows with counts: the shortest window with everything you need
🌍 In real life. A market street has one shop after another: a for atta, b for biscuits, c for chal (rice), and plenty of others. Your list says atta, biscuits and chal. Which shortest stretch of shops sells all three? Walk along adding shops until your stretch has everything. Then drop shops from the start of the stretch as long as it still has everything, noting the shortest. When dropping one more would lose an item, walk on again.
This time the window's rule needs counts: "at least this many of each".
The idea in one sentence: grow the window until it covers every needed letter (with enough copies), then shrink it from the left while it still covers them, remembering the shortest covering window.
Its words:
- want: how many of each letter you need, a dict built from the word:
"aab"→{"a": 2, "b": 1} - have: how many of each letter the window holds now
- covered: how many different letters have
have[ch] >= want[ch]; the window covers everything whencovered == len(want)
How it works, step by step:
- grow: add
text[r]tohave; if that letter just reached its target,covered += 1 - while
covered == len(want): the windowtext[l:r + 1]works, so keep it if it is the shortest; then removetext[l]fromhave(if it drops below its target,covered -= 1) and move l right
Watch the window find "cba" in "adobecbanc":
Why it is correct. Take the shortest window that covers everything, from position a to position b. l never moves past a before r reaches b: that would need a covering window starting at a and ending before b, which would be even shorter. So when r reaches b, the window covers and starts at a or earlier, and the shrinking goes on while it still covers: l reaches a, and the window from a to b is recorded.
What it costs, worked out. Again each letter comes in once and goes out at most once: at most 2n moves, each a few O(1) dict updates, so O(n) for a text of n letters. Checking every start and end and counting each window would be O(n³), or O(n²) with clever counting: for 10,000 letters, 50 million windows against 20,000 moves.
Why covered, not comparing dicts? Comparing have with want after every move costs one step per different letter; the single number covered changes only when a letter crosses its target, so the check is one step.
def min_window(text, need):
want = {}
for ch in need:
want[ch] = want.get(ch, 0) + 1
have = {}
covered = l = 0
best = ""
for r, ch in enumerate(text):
have[ch] = have.get(ch, 0) + 1
if ch in want and have[ch] == want[ch]:
covered += 1
while covered == len(want):
if not best or r + 1 - l < len(best):
best = text[l:r + 1]
out = text[l]
have[out] -= 1
if out in want and have[out] < want[out]:
covered -= 1
l += 1
return best
print(min_window("adobecbanc", "abc"))
print(min_window("banana", "aan"))
print(repr(min_window("abc", "z")))Mistakes and edge cases.
- counting
coveredup every time a needed letter comes in (not only when it reaches its target) overcounts repeats - forgetting repeats in
need: "aan" needs two a's, so a window with one a doesn't cover it - updating the best after removing
text[l]measures the wrong window - if some needed letter never appears, there is no answer: return ""
Quiz
What does this print?
want = {} for ch in "aab": want[ch] = want.get(ch, 0) + 1 print(want, len(want))When does
coveredgo up by 1?- When a needed letter's count in the window reaches exactly what is wanted
- Every time any letter comes in
- Every time a needed letter comes in
Does the window text[1:4] of "banana" have two a's and an n? What does this print?
text = "banana" w = text[1:4] print(w, w.count("a") >= 2 and "n" in w)Why is the window search O(n) for a text of n letters?
- Each letter enters once and leaves at most once, and each move is a few O(1) dict updates
- It compares the two dicts after every move
- It only looks at the needed letters
min_window("adobecbanc", "abc") should be "banc", but this answers "dobecba". Which line is wrong?
def min_window(text, need): want = {} for ch in need: want[ch] = want.get(ch, 0) + 1 have = {} covered = l = 0 best = "" for r, ch in enumerate(text): have[ch] = have.get(ch, 0) + 1 if ch in want and have[ch] == want[ch]: covered += 1 while covered == len(want): if not best or r + 1 - l > len(best): best = text[l:r + 1] out = text[l] have[out] -= 1 if out in want and have[out] < want[out]: covered -= 1 l += 1 return best
Coding tasks
Write
min_window(text, need): the shortest stretch oftextthat contains every letter ofneed, as many times as it appears inneed(the first one if several are equally short), or "" if there is none.Write
distinct_in_windows(text, k)with a fixed window and a dict of counts: for every window of k letters, in order, how many different letters it has. If k is bigger than the text, give back [].