Minimum Window Substring
The problem
Section titled “The problem”You get strings s and t. Return the shortest substring of s that contains every
character of t, including repeats (if t has two As, the window needs two). Return
"" if no such substring exists.
s = "ADOBECODEBANC", t = "ABC" -> "BANC"Key insight
Section titled “Key insight”Brute force checks every substring of s, which is O(m² · n) or worse. Instead, slide a
window and track what is still missing.
Keep a need count per character (start with the counts in t) and a single number
missing, the count of required characters not yet covered. Expanding right over a
needed character lowers missing. When missing hits 0 the window is valid, so shrink
from the left: drop surplus characters (their need is negative) for free, record the
window, then drop one required character to make it invalid and keep expanding. The
single missing counter avoids re-comparing two maps at every step.
Show solutionHide solution
from collections import Counter
def min_window(s: str, t: str) -> str: need = Counter(t) # how many of each char the window must contain missing = len(t) # how many required chars are still uncovered best_start, best_len = 0, float("inf") left = 0 for right, ch in enumerate(s): if need[ch] > 0: # this char was still needed missing -= 1 need[ch] -= 1 # may go negative: surplus copy if missing == 0: # window is valid: shrink from the left while need[s[left]] < 0: # leftmost char is surplus need[s[left]] += 1 left += 1 if right - left + 1 < best_len: best_start, best_len = left, right - left + 1 need[s[left]] += 1 # drop a required char; window is invalid again missing += 1 left += 1 return "" if best_len == float("inf") else s[best_start:best_start + best_len]export function minWindow(s: string, t: string): string { const need = new Map<string, number>(); // chars still needed; negative = surplus for (const ch of t) need.set(ch, (need.get(ch) ?? 0) + 1); let missing = t.length; // required chars not yet covered let bestStart = 0; let bestLen = Infinity; let left = 0; for (let right = 0; right < s.length; right++) { const ch = s[right]; if ((need.get(ch) ?? 0) > 0) missing--; // this char was still needed need.set(ch, (need.get(ch) ?? 0) - 1); if (missing === 0) { while ((need.get(s[left]) ?? 0) < 0) { // leftmost char is surplus need.set(s[left], need.get(s[left])! + 1); left++; } if (right - left + 1 < bestLen) { bestStart = left; bestLen = right - left + 1; } need.set(s[left], need.get(s[left])! + 1); // drop a required char missing++; left++; } } return bestLen === Infinity ? '' : s.substring(bestStart, bestStart + bestLen);}class Solution { public String minWindow(String s, String t) { int[] need = new int[128]; // chars still needed; negative = surplus for (char c : t.toCharArray()) need[c]++; int missing = t.length(); // required chars not yet covered int bestStart = 0, bestLen = Integer.MAX_VALUE; int left = 0; for (int right = 0; right < s.length(); right++) { if (need[s.charAt(right)] > 0) missing--; // this char was still needed need[s.charAt(right)]--; if (missing == 0) { while (need[s.charAt(left)] < 0) { // leftmost char is surplus need[s.charAt(left)]++; left++; } if (right - left + 1 < bestLen) { bestStart = left; bestLen = right - left + 1; } need[s.charAt(left)]++; // drop a required char missing++; left++; } } return bestLen == Integer.MAX_VALUE ? "" : s.substring(bestStart, bestStart + bestLen); }}Complexity
Section titled “Complexity”- Time: O(m + n) —
m = len(s),n = len(t). Buildingneedis O(n). Thenrightandlefteach move forward at most m times. - Space: O(k) — the count table, where
kis the number of distinct characters.
Watch out for
Section titled “Watch out for”- Duplicates in
tmatter. Track counts, not a set.t = "aa"needs twoas. - Decrement
needfor every character, even ones not int. They go negative, which is how the shrink loop recognizes surplus. Only decrementmissingwhenneedwas positive before the decrement. - Return
""when nothing fits, and take the substring only after the loop, using the saved start and length.
Variations
Section titled “Variations”Find All Anagrams in a String (LeetCode 438)
Section titled “Find All Anagrams in a String (LeetCode 438)”Return every start index where s has an anagram of p. The trick: a fixed-size
window of len(p) with a character count. Slide it and compare counts (or keep a
single matched counter like missing).
Permutation in String (LeetCode 567)
Section titled “Permutation in String (LeetCode 567)”Same fixed-size window, but only ask “does any window match?” The trick: stop at the
first window where the counts equal those of s1.
Substring with Concatenation of All Words (LeetCode 30)
Section titled “Substring with Concatenation of All Words (LeetCode 30)”Find where s is a concatenation of all given equal-length words. The trick: slide
over word-sized steps instead of characters, one pass for each offset 0..wordLen-1,
with a word-count map playing the role of need.