Skip to content

Minimum Window Substring

HardLeetCode #76Time O(m + n)Space O(k)

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"

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]
  • Time: O(m + n) — m = len(s), n = len(t). Building need is O(n). Then right and left each move forward at most m times.
  • Space: O(k) — the count table, where k is the number of distinct characters.
  • Duplicates in t matter. Track counts, not a set. t = "aa" needs two as.
  • Decrement need for every character, even ones not in t. They go negative, which is how the shrink loop recognizes surplus. Only decrement missing when need was positive before the decrement.
  • Return "" when nothing fits, and take the substring only after the loop, using the saved start and length.

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).

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.