76. Minimum Window Substring
1. Description
Given two strings s and t of lengths m and n respectively, return the minimum window substring of s such that every character in t (including duplicates) is included in the window. If there is no such substring, return the empty string “”.
The testcases will be generated such that the answer is unique.
2. Example
Example 1
Input: s = “ADOBECODEBANC”, t = “ABC”
Output: “BANC”
Explanation: The minimum window substring “BANC” includes ‘A’, ‘B’, and ‘C’ from string t.
Example 2
Input: s = “a”, t = “a”
Output: “a”
Explanation: The entire string s is the minimum window.
Example 3
Input: s = “a”, t = “aa”
Output: ""
Explanation: Both ‘a’s from t must be included in the window.
Since the largest window of s only has one ‘a’, return empty string.
3. Constraints
- m == s.length
- n == t.length
- 1 <= m, n <= 105
- s and t consist of uppercase and lowercase English letters.
4. Solutions
Sliding Window
m = s.size(), n = t.size()
Time complexity: O(m+ n)
Space complexity: O(1)
class Solution {
public:
string minWindow(const string &s, const string &t) {
const int m = s.size(), n = t.size();
if (m < n) {
return "";
}
array<int, 52> required_letter_count = {}, letter_count = {};
for (char letter : t) {
++required_letter_count[index(letter)];
}
int count = 0, left = 0, right = 0;
int best_left = 0, best_right = numeric_limits<int>::max();
while (right < m) {
int right_index = index(s[right]);
++right;
++letter_count[right_index];
if (letter_count[right_index] <= required_letter_count[right_index]) {
++count;
}
while (left < m) {
int left_index = index(s[left]);
if (letter_count[left_index] > required_letter_count[left_index]) {
--letter_count[left_index];
++left;
} else {
break;
}
}
if (count == n && (right - left < best_right - best_left)) {
best_left = left;
best_right = right;
}
}
return best_right == numeric_limits<int>::max()
? ""
: s.substr(best_left, best_right - best_left);
}
private:
int index(char letter) {
return letter <= 'Z' ? letter - 'A' : letter - 'a' + 26;
}
};