Medium
Minimum Window Substring
👶 The 5-Year-Old Summary
Find smallest window containing all characters of "t"! "ADOBECODEBANC" with "ABC" → "BANC"!
🎮 Interactive Visualizer
s = "ADOBECODEBANC", t = "ABC"
🧠The Brain Hack
Expand right, shrink left! Use hash map to count required chars. When all chars found, shrink from left while still valid. Track smallest window!
💻 The Clean Solution
def min_window(s, t):
if not t or not s: return ""
# Count required chars
need = Counter(t)
window = {}
have, needlen = 0, len(need)
left = 0
result = float('inf'), None
for right in range(len(s)):
c = s[right]
window[c] = window.get(c, 0) + 1
if c in need and window[c] == need[c]:
have += 1
while have == needlen:
# Update result
if right - left + 1 < result[0]:
result = (right - left + 1, s[left:right+1])
# Shrink window from left
[s[left]] -= 1
if s[left] in need and window[s[left]] < need[s[left]]:
have -= 1
left += 1
return result[1] if result[1] else ""
# "ADOBECODEBANC", "ABC" → "BANC"
Time: O(n)
Space: O(alphabet)