Introduction
The Minimum Window Substring problem involves finding the smallest substring that contains all characters of another string.
Given:
- a string s
- a string t
the task is to:
- find the minimum substring of s
- containing all characters of t
- including duplicates
If no such substring exists:
- return empty string
This problem is one of the most important applications of:
Sliding Window TechniqueThis problem helps in understanding:
- hashing
- frequency tracking
- dynamic window resizing
- substring optimization
Example
Input:s = "ADOBECODEBANC"
t = "ABC"
Output: "BANC"
Explanation: "BANC" contains: A, B, C and is the minimum valid window.
Input:
s = "a"
t = "aa"
Output:
""
Explanation: Required characters are not available.
Constraints
1 <= s.length, t.length <= 10^5s and t contain English lettersApproach 1 : Brute Force
Explanation
The simplest way to solve this problem is:
- Generate all substrings
- Check whether substring contains all characters of
t - Track smallest valid substring
This approach works but checking all substrings increases time complexity.
Steps
- Generate all substrings.
- Count substring frequencies.
- Compare with target frequencies.
- If valid:
- update minimum window
- Return smallest substring.
Dry Run
Input:s = "ADOBECODEBANC"
t = "ABC"
Check substrings:
"A" → invalid "ADOBEC" → valid Length = 6 Continue searching... "BANC" → valid Length = 4
Minimum window updated
Final Result: "BANC"
Brute Force Code
Complexity Analysis
Time Complexity: O(n³)Explanation:
All substrings are generated and checked.
Space Complexity: O(n) Explanation:
Extra hashmap is used.
Approach 2 : Optimized Solution (Sliding Window)
Explanation
The optimized solution uses the Sliding Window Technique.
The idea is:
- Expand window using right pointer
- Track character frequencies
- When window becomes valid:
- shrink from left
- Track minimum valid window
This avoids checking all substrings repeatedly.
Steps
- Store target frequencies.
- Initialize:
- left = 0
- right = 0
- Expand window.
- Update matched characters.
- Shrink valid window.
- Track minimum substring.
Dry Run
Input:s = "ADOBECODEBANC" t = "ABC"
Expand window: "ADOBEC"
All characters found Current length = 6
Shrink window Continue traversal...
Window becomes: "BANC" Length = 4 Minimum window updated
Final Result: "BANC"
Optimized Code
Complexity Analysis
Time Complexity: O(n)
Explanation:
Each character is visited at most twice.
Space Complexity: O(n)
Explanation:
Hashmaps store character frequencies.