Minimum Window Substring
LeetCode 76 · Hard · solution, intuition & step-by-step walkthrough
Expand to valid, shrink to minimal; 'formed' counts satisfied characters.
This is how I solved Minimum Window Substring (LeetCode 76), a hard problem from the Sliding Window pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.
Intuition
Expand the right edge until the window contains every required character in the right quantity; then shrink from the left as far as possible while it stays valid, recording the smallest window. Repeat for every right edge.
Approach
- 1
Count requirements from t; required = number of distinct characters.
- 2
Add s[r] to the window; when its count reaches the need, formed++.
- 3
While formed == required: record the window, remove s[l], update formed, l++.
- 4
Return the best window.
How I solved it
Sliding window with countsPythonO(n) time
class Solution:
def minWindow(self, s: str, t: str) -> str:
req_freq_map = Counter(t)
required = len(req_freq_map)
window_map_freq = defaultdict(int)
l=0
r=0
s_index=None
r_index=None
formed=0
min_length = float("inf")
while r<len(s):
char=s[r]
window_map_freq[char]+=1
if char in req_freq_map and window_map_freq[char]==req_freq_map[char]:
formed+=1
#shrink
while l<=r and formed==required:
left_most_char = s[l]
window_map_freq[left_most_char]-=1
if r-l+1<min_length:
min_length = r-l+1
s_index=l
r_index=r
if left_most_char in req_freq_map and window_map_freq[left_most_char]<req_freq_map[left_most_char]:
formed-=1
l+=1
r+=1
return s[s_index:r_index+1] if s_index!=None and r_index!=None else ""
Minimum Window Substring — FAQ
What is the intuition behind Minimum Window Substring?
Expand the right edge until the window contains every required character in the right quantity; then shrink from the left as far as possible while it stays valid, recording the smallest window. Repeat for every right edge.
How do you solve Minimum Window Substring (LeetCode 76)?
1. Count requirements from t; required = number of distinct characters. 2. Add s[r] to the window; when its count reaches the need, formed++. 3. While formed == required: record the window, remove s[l], update formed, l++. 4. Return the best window.
What is the time and space complexity of Minimum Window Substring?
Time: O(|s| + |t|). Space: O(Σ). (Accepted approach: Sliding window with counts.)
What are common mistakes in Minimum Window Substring?
formed should change only when a count crosses the requirement exactly. Return '' when no window is ever valid.