What is Minimum Window
Return the shortest substring of s that contains every character of t, including duplicates. If several windows share that length, return the leftmost. If none exists, the practice output is a blank line. This picture shows none.
ADOBECODEBANC ABC BANC
Approach
Interactive solution
The finished picture is on screen when the page opens. Next and Play start again from the first step. L and R mark the window.
Complexity
| Piece | Cost | Why |
|---|---|---|
| Time | O(n) | Each character of s enters and leaves once. |
| Memory | O(1) | The count tables are bounded by the alphabet, and t is short. |
Implementation
def min_window(s, t):
need = {}
for ch in t:
need[ch] = need.get(ch, 0) + 1
have = 0
required = len(need)
window, l, best = {}, 0, None
for r, ch in enumerate(s):
window[ch] = window.get(ch, 0) + 1
if ch in need and window[ch] == need[ch]:
have += 1
while have == required and l <= r:
if best is None or r - l + 1 < best[1] - best[0] + 1:
best = (l, r)
left = s[l]
window[left] -= 1
if left in need and window[left] < need[left]:
have -= 1
l += 1
if best is None:
return ""
return s[best[0]:best[1] + 1]