76. Minimum Window Substring ๐
Difficulty: Hard
- Tags: String
, Sliding Window
, Hash Table
Problem Statement ๐
Given two strings s
and t
, return the minimum window substring of s
such that every character in t
(including duplicates) is included in the window. If no such substring exists, return the empty string ""
.
Examples ๐
๐น Example 1:
Input:
Output:
Explanation: The substring "BANC" is the smallest window in s
that contains all the characters of t
.
๐น Example 2:
Input:
Output:
Explanation: The entire string s
is the minimum window.
๐น Example 3:
Input:
Output:
Explanation: Both 'a's from t
must be included in the window. Since s
only has one 'a', there is no valid substring.
Constraints โ๏ธ
1 <= m, n <= 10^5
wherem
is the length ofs
andn
is the length oft
.s
andt
consist of uppercase and lowercase English letters.
๐ค Follow-up: Could you solve the problem in O(m + n)
time?
Solution ๐ก
To solve this problem efficiently, we use the Sliding Window technique with two pointers and a frequency counter:
Count Frequencies:
Use a hash map to count the frequency of characters in
t
.
Sliding Window:
Expand the window by moving the right pointer until all characters in
t
are included in the current window.Shrink the window from the left while maintaining the validity of the window, and update the result if the current window is smaller.
Track Validity:
Use a counter to track how many unique characters from
t
have been fully matched in the current window.
Return Result:
If no valid window is found, return
""
. Otherwise, return the smallest valid window.
Java Solution
Time Complexity โณ
O(m + n):
Traversing the string
s
takesO(m)
.Updating the frequency hash maps and shrinking the window is linear relative to the size of
s
andt
.
Space Complexity ๐พ
O(n):
Hash maps are used to store the frequencies of characters in
t
and the sliding window.
You can find the full solution here.
Last updated