Minimum Window Substring
Difficulty: Hard · Pattern: Sliding Window · LeetCode #76
Given strings s and t, return the shortest substring of s that contains every character of t with multiplicity (if t has two a's, the window needs at least two). If none exists, return "". The answer is unique when it exists.
Examples
s = "XADOBECODEBANCY", t = "ABC" → "BANC"
s = "aa", t = "aa" → "aa"
s = "a", t = "b" → ""Hints
- Expand the right edge until the window contains everything in
t. - Then shrink from the left as long as the window stays valid, recording the smallest size.
- Track
missing, the number of required characters not yet covered, to test validity in O(1).
Approach
Let need[c] = count of c still required (initialized from t), and missing = len(t). Move r right: if need[s[r]] > 0, it fills a requirement, so missing −= 1; then decrement need[s[r]] (it may go negative, meaning surplus).
When missing == 0 the window is valid: shrink from l while need[s[l]] < 0 (surplus characters), record the window, then give up s[l] (making missing = 1) and continue expanding. Each index moves at most twice: O(|s| + |t|).
Complexity
Time: O(|s| + |t|). Space: O(alphabet).
Python solution
from collections import Counter
def minWindow(s, t):
need = Counter(t)
missing = len(t)
l = 0
best = (float('inf'), 0, 0)
for r, c in enumerate(s):
if need[c] > 0:
missing -= 1
need[c] -= 1
if missing == 0:
while need[s[l]] < 0: # drop surplus chars from the left
need[s[l]] += 1
l += 1
if r - l + 1 < best[0]:
best = (r - l + 1, l, r + 1)
need[s[l]] += 1 # give up a required char, keep searching
missing += 1
l += 1
return "" if best[0] == float('inf') else s[best[1]:best[2]]JavaScript solution
function minWindow(s, t) {
const need = new Map();
for (const c of t) need.set(c, (need.get(c) || 0) + 1);
let missing = t.length, l = 0, bestLen = Infinity, bestL = 0;
for (let r = 0; r < s.length; r++) {
const c = s[r];
if ((need.get(c) || 0) > 0) missing--;
need.set(c, (need.get(c) || 0) - 1);
if (missing === 0) {
while (need.get(s[l]) < 0) { need.set(s[l], need.get(s[l]) + 1); l++; }
if (r - l + 1 < bestLen) { bestLen = r - l + 1; bestL = l; }
need.set(s[l], need.get(s[l]) + 1); missing++; l++;
}
}
return bestLen === Infinity ? '' : s.slice(bestL, bestL + bestLen);
}