Full answer
Problem
Given s and t, return the minimum-length substring of s that contains every character of t with at least the same multiplicity. Return "" if none exists.
Example: s = "ADOBECODEBANC", t = "ABC" gives "BANC".
Constraints: 1 <= len(s), len(t) <= 10^5, upper and lowercase letters. The answer is unique.
Brute force
Check every substring for coverage: O(n^2) substrings, each checked in O(alphabet) with counts, O(n^2) or worse.
Optimal approach
need = Counter(t);missing = len(t).- For each
right:- If
need[s[right]] > 0, this character fills a gap:missing -= 1. need[s[right]] -= 1(it may go negative for surplus characters).
- If
- While
missing == 0(valid window):- Record the window if it is the shortest so far.
- Give back
s[left]:need[s[left]] += 1; if it becomes positive, the window now lacks it, somissing += 1. left += 1.
Why it works
need[c] is the number of c still required (negative means surplus). missing is the total still required, so missing == 0 means the window covers t. For each right edge, shrinking until the window becomes invalid finds the shortest valid window ending at that edge. The overall minimum is among those, and both pointers only move forward, so every window that matters is examined.
Complexity
O(|s| + |t|) time. O(alphabet size) space.
Code
from collections import Counter
def min_window(s, t):
"""Smallest substring of s containing every character of t (with counts). O(|s| + |t|)."""
if not t or not s:
return ""
need = Counter(t)
missing = len(t) # characters of t still not covered
left = 0
best = (float("inf"), 0, 0) # (length, start, end exclusive)
for right, ch in enumerate(s):
if need[ch] > 0:
missing -= 1
need[ch] -= 1
while missing == 0: # window is valid: shrink from the left
if right - left + 1 < best[0]:
best = (right - left + 1, left, right + 1)
need[s[left]] += 1
if need[s[left]] > 0:
missing += 1
left += 1
return "" if best[0] == float("inf") else s[best[1]:best[2]]
def brute(s, t):
need = Counter(t)
best = ""
for i in range(len(s)):
for j in range(i + 1, len(s) + 1):
if not need - Counter(s[i:j]) and (not best or j - i < len(best)):
best = s[i:j]
return best if t else ""
if __name__ == "__main__":
for f in (min_window, brute):
assert f("ADOBECODEBANC", "ABC") == "BANC"
assert f("a", "a") == "a"
assert f("a", "aa") == ""
assert f("", "a") == ""
assert f("abc", "") == ""
assert f("aaflslflsldkalskaaa", "aaa") == "aaa"
print("all tests passed")Save as a25_min_window.py and run python3 a25_min_window.py. It prints all tests passed (Python 3.13.5).
Edge cases
t longer than s or characters of t missing from s (return ""). Repeated characters in t ("aa" needs two as). Empty t returns "" by convention here. Case sensitivity: "a" and "A" are different.
Pattern
Variable window with "at least" counts and a single satisfied counter. The structure is the general sliding window template: expand until valid, then shrink while valid, updating the answer inside the shrink loop.
from collections import Counter
def min_window(s, t):
"""Smallest substring of s containing every character of t (with counts). O(|s| + |t|)."""
if not t or not s:
return ""
need = Counter(t)
missing = len(t) # characters of t still not covered
left = 0
best = (float("inf"), 0, 0) # (length, start, end exclusive)
for right, ch in enumerate(s):
if need[ch] > 0:
missing -= 1
need[ch] -= 1
while missing == 0: # window is valid: shrink from the left
if right - left + 1 < best[0]:
best = (right - left + 1, left, right + 1)
need[s[left]] += 1
if need[s[left]] > 0:
missing += 1
left += 1
return "" if best[0] == float("inf") else s[best[1]:best[2]]
def brute(s, t):
need = Counter(t)
best = ""
for i in range(len(s)):
for j in range(i + 1, len(s) + 1):
if not need - Counter(s[i:j]) and (not best or j - i < len(best)):
best = s[i:j]
return best if t else ""
if __name__ == "__main__":
for f in (min_window, brute):
assert f("ADOBECODEBANC", "ABC") == "BANC"
assert f("a", "a") == "a"
assert f("a", "aa") == ""
assert f("", "a") == ""
assert f("abc", "") == ""
assert f("aaflslflsldkalskaaa", "aaa") == "aaa"
print("all tests passed")Single missing counter over a Counter of needs; a brute force is cross-checked on small cases.
Complexity
Time: O(|s| + |t|). Space: O(alphabet size). need values go negative for surplus characters, which is what makes the missing counter work.
By level
Fresher: Explains the expand-then-shrink idea with a count map and traces the example at a high level. Should test a t with repeated characters.
Mid: Implements the missing counter correctly, handles repeats and explains why the scan is linear. Records the answer inside the shrink loop.
Senior: Generalises the template, handles ordered variants (minimum window subsequence with DP or two pointers) and discusses streaming or very large alphabets. Can explain the cost of the method when the alphabet is large.
Key points
- Count what t needs
- Expand right until nothing is missing
- Shrink left while still valid, recording the best
- A single missing counter avoids comparing maps
- O(|s| + |t|) time
Common mistakes
- Ignoring repeated characters in t
- Recording the window after shrinking past validity
- Comparing whole count maps on every step
- Moving left in an if instead of a while
Follow-ups
- How would you return the count of such windows?
- What if t's characters must appear in order?
- How would you handle a stream of characters?
Tips
- Explain the need map and missing counter first
- Narrate expand and shrink phases
- Test t with repeated characters
Evaluation rubric
- Correct O(n) algorithm
- Handles multiplicities
- Records the best window correctly
- Clear explanation of the invariant