Find the shortest stretch of s holding every letter of t. Grow the window right until it's complete, then shrink from the left while it stays so.
▼The problem
LeetCode 76 (Hard). Given strings s and t, return the shortest substring of s that contains every character of t, duplicates included, or "" if there is none.
Example: s = "ADOBECODEBANC", t = "ABC" → "BANC".
from collections import Counter
def min_window(s, t):
need = Counter(t)
have, formed = Counter(), 0
best, left = "", 0
for right, ch in enumerate(s):
have[ch] += 1
if have[ch] == need[ch]:
formed += 1
while formed == len(need):
if not best or right - left + 1 < len(best):
best = s[left:right + 1]
out = s[left]
have[out] -= 1
if have[out] < need[out]:
formed -= 1
left += 1
return bestTRY IT ON LEETCODE ▶The solution
from collections import Counter
def min_window(s, t):
need = Counter(t)
have, formed = Counter(), 0
best, left = "", 0
for right, ch in enumerate(s):
have[ch] += 1
if have[ch] == need[ch]:
formed += 1
while formed == len(need):
if not best or right - left + 1 < len(best):
best = s[left:right + 1]
out = s[left]
have[out] -= 1
if have[out] < need[out]:
formed -= 1
left += 1
return bestTranscript
Minimum Window Substring. You get two strings, s and t. Find the shortest piece of s that holds every letter of t, repeats included: if t has N twice, the window needs N twice. If no piece works, return the empty string.
Take this thirteen letter string, and t equals A, B, C. The first six letters already hold all three. But look further along, and the shortest window is B, A, N, C: just four letters.
The simple way tries every start and every end, and counts the letters in each window. Thirteen letters make ninety-one windows. With m letters, that's about m squared windows, and every count costs more steps. Too slow.
Instead, slide one window, like a velvet rope. Keep a want list of what t needs, and count how many letters are covered. Stretch the right edge until all of them are. Then pull the left edge in while it still covers t, saving the shortest. When it breaks, stretch right again.
Let's run it. Stretch right: A, B, then C at index five. All covered: save six. Pull left, and losing A breaks it. Stretch to the next A, at index ten. Ten letters, no better. Pull left past D, O, B and E, until losing C breaks it again. Stretch to the last C, then pull left: seven, six, five, four. Losing B breaks it, and the string is done. B, A, N, C!
In code, count t's letters. Add each right letter; if its count just reached the need, one more letter is formed. While all are formed, save the window if it's shorter, drop the left letter, and if that falls short, formed goes down.
Each letter enters the window once and leaves at most once. With n letters in t, that's order m plus n time. The counts hold one entry per distinct letter: order k space.
Stretch to cover, shrink to the shortest, repeat. That's Minimum Window Substring.