Data Structures & AlgorithmsVery hardProduct Company SDE · Amazon/Microsoft-style OA

Problem: Return the smallest window of s that contains every character of t (with multiplicity).

Problem: Return the smallest window of s that contains every character of t (with multiplicity).
from collections import Counter
def min_window(s, t):
    need, missing = Counter(t), len(t)
    l = 0; best = (0, float('inf'))
    for r, ch in enumerate(s):
        if need[ch] > 0:
            missing -= 1
        need[ch] -= 1
        while missing == 0:
            if r - l < best[1] - best[0]:
                best = (l, r)
            need[s[l]] += 1
            if need[s[l]] > 0:
                missing += 1
            l += 1
    return "" if best[1] == float('inf') else s[best[0]:best[1] + 1]
print(min_window("XAYBZAXB", "ABX"))
What is printed?
  1. A. XAYB
  2. B. BZAX
  3. C. AXB
  4. D. ZAXB

Correct answer: C. AXB

Expand until every needed letter is covered (missing = 0), then shrink from the left while it stays covered. The first valid window is XAYB (length 4), later BZAX (length 4), and finally AXB at indices 5..7 (length 3), the shortest. Each pointer moves at most n times: O(|s| + |t|). Returning the first valid window (XAYB) is the usual mistake.

More Coding Interview Problems questions

Exams that ask this topic