Minimum Window Substring
Find the shortest substring of s that contains every character of t, counts included, with a sliding window.
The problem
You get two strings s and t made of uppercase and lowercase English letters. Return the shortest substring of s that contains every character of t, repeats included: if t has two a's, the window needs at least two. If no such substring exists, return the empty string; when one exists, you can assume the shortest one is unique.
Input s = "ZEBRAXCABE", t = "ABC"
Output "CAB"
"CAB" holds A, B and C in three letters; every other window with all three is longer.
Input s = "lemon", t = "mm"
Output ""
t needs two m's, but s has only one, so no window works.
Key constraint: Both strings can be up to 100,000 characters, so checking every substring is far too slow.
How to spot the pattern
- You need the shortest contiguous stretch that covers a set of required items, counts included.
- Once a window covers everything, you can shrink it from the left, and growing on the right only adds coverage.
The idea
Count what t needs, then grow a window over s with a right pointer, tracking how many of the required characters it already covers. As soon as it covers all of them, shrink it from the left while it still does, recording the shortest window you see. When a removal breaks the coverage, go back to growing on the right.
Brute force: For every start, extend the window until it covers t, which takes O(n^2) time in the worst case.
Step by step
- 1Count the characters of
tinneed, and setmissing = len(t), the number of characters still to cover. - 2Move
rightacrosss: ifneed[s[right]] > 0, decreasemissing, and decreaseneed[s[right]]either way. - 3While
missing == 0, record the window if it is the shortest so far, then give backs[left]by increasingneed[s[left]]. - 4If that count is now positive, the window lost a required character, so increase
missing; then moveleftforward. - 5Return the shortest window found, or the empty string.
See the pattern move
The sliding window pattern on a small example. Step through it, or press play.
Code
from collections import Counter
class Solution:
def minWindow(self, s: str, t: str) -> str:
need = Counter(t) # how many more of each character the window needs
missing = len(t) # required characters not yet covered
left = 0
best_start, best_len = 0, float("inf")
for right, ch in enumerate(s):
if need[ch] > 0:
missing -= 1
need[ch] -= 1
while missing == 0: # the window covers t: try to shrink it
if right - left + 1 < best_len:
best_start, best_len = left, right - left + 1
need[s[left]] += 1
if need[s[left]] > 0:
missing += 1 # we just gave away a required character
left += 1
return "" if best_len == float("inf") else s[best_start:best_start + best_len]Complexity
Time
O(n + m)
Space
O(1)
Counting t takes O(m), and right and left each cross s once; the counts live in a fixed array of 128 slots.
Watch out for
- Ignoring repeats in
t: "AAB" needs two A's, so a set of characters is not enough; count them. - Decreasing
missingfor every character that enters, even ones the window already has enough of; only decrease it while that character's count is still positive. - Slicing out a new substring every time you find a shorter window; store its start and length and slice once at the end.
Follow-up questions
Why can both pointers only move forward?
Once a window covers t, every window ending at the same place but starting earlier also covers it, so the only useful move is to shrink from the left. And once it stops covering, starting earlier again can't help, because those windows were already checked.
What if s is huge but only a few of its characters appear in t?
First list the positions in s whose characters appear in t, then run the window over that shorter list. The answer is the same, with less work.
In Hinglish
Right se tab tak badhao jab tak t ke saare characters (ginti ke saath) cover na ho jaayein, phir left se jitna ho sake chhota karo aur sabse chhoti window yaad rakho.