SDE & MLE Prep

76. Minimum Window Substring

Problem

Return the shortest substring of s that contains every character of t, duplicates included (two as in t need two as in the window). Return "" if there is none; the answer is unique when it exists.

Example: s = "ADOBECODEBANC", t = "ABC" → "BANC"

Constraints: lengths ≤ 10⁵. Follow-up: O(m + n).

Expand r until the window covers all of t (missing == 0), then shrink l as far as possible while still covering, recording the smallest window.

s = ADOBECODEBANC, t = ABC
[ADOBEC]ODEBANC      covers -> shrink: drop A -> missing A
 ADOBEC[ODEBA]NC     ...
 ADOBECODE[BANC]     covers, len 4  <- answer "BANC"

Complexity: O(|s| + |t|).

class Solution:
    def minWindow(self, s: str, t: str) -> str:
        need = Counter(t)
        missing = len(t)
        l = start = 0
        best = float("inf")
        for r, ch in enumerate(s):
            if need[ch] > 0:
                missing -= 1
            need[ch] -= 1
            while missing == 0:
                if r - l + 1 < best:
                    start, best = l, r - l + 1
                need[s[l]] += 1
                if need[s[l]] > 0:
                    missing += 1
                l += 1
        return "" if best == float("inf") else s[start:start + best]