Minimum Window Substring - Problem
Find the Smallest Window Containing All Characters
You're given two strings: a source string
Think of it as finding the smallest "net" that can capture all the required "fish" from the target string. If no such window exists, return an empty string.
Key Points:
• The window must contain all characters from
• Duplicate characters in
• Among all valid windows, return the shortest one
• The answer is guaranteed to be unique
Example: If
You're given two strings: a source string
s and a target string t. Your mission is to find the shortest contiguous substring within s that contains every character from t (including duplicates).Think of it as finding the smallest "net" that can capture all the required "fish" from the target string. If no such window exists, return an empty string.
Key Points:
• The window must contain all characters from
t• Duplicate characters in
t must appear at least that many times in the window• Among all valid windows, return the shortest one
• The answer is guaranteed to be unique
Example: If
s = "ADOBECODEBANC" and t = "ABC", the minimum window is "BANC". Input & Output
example_1.py — Basic Case
$
Input:
s = "ADOBECODEBANC", t = "ABC"
›
Output:
"BANC"
💡 Note:
The minimum window substring "BANC" includes all characters from "ABC". Other valid windows like "ADOBEC" are longer.
example_2.py — Single Character
$
Input:
s = "a", t = "a"
›
Output:
"a"
💡 Note:
The entire string s is the minimum window containing all characters of t.
example_3.py — No Valid Window
$
Input:
s = "a", t = "aa"
›
Output:
""
💡 Note:
There's no substring in s that contains two 'a' characters, so return empty string.
Visualization
Tap to expand
Understanding the Visualization
1
Setup Target
Count all the stars (characters) you need to find
2
Expand Window
Widen your telescope view until you can see all required stars
3
Contract Window
Narrow the view while keeping all stars visible
4
Track Minimum
Remember the smallest window that worked
5
Continue Sliding
Move the window and repeat until you've checked the entire sky
Key Takeaway
🎯 Key Insight: The sliding window technique transforms an O(n³) brute force approach into an elegant O(n) solution by intelligently expanding and contracting a single window, ensuring each character is visited at most twice!
Time & Space Complexity
Time Complexity
O(n + m)
One pass through string s (n) plus one pass to build frequency map of t (m)
✓ Linear Growth
Space Complexity
O(m + k)
Hash maps for character frequencies, where k is the number of unique characters
✓ Linear Space
Constraints
- m == s.length
- n == t.length
- 1 ≤ m, n ≤ 105
- s and t consist of uppercase and lowercase English letters
- The answer is guaranteed to be unique
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code