Python3 Solution:
from collections import defaultdict
class Solution:
def minWindow(self, s: str, t: str) -> str:
need = defaultdict(int)
window = defaultdict(int)
for ch in t:
need[ch] += 1
left, right = 0, 0
valid = 0
start, nlen = 0, float('inf')
while right < len(s):
ch = s[right]
right += 1
if ch in need:
window[ch] += 1
if window[ch] == need[ch]:
valid += 1
while valid == len(need):
if right - left < nlen:
start = left
nlen = right - left
ch = s[left]
left += 1
if ch in need:
if window[ch] == need[ch]:
valid -= 1
window[ch] -= 1
return "" if nlen == float('inf') else s[start:start+nlen]
C++ Solution:
class Solution {
public:
string minWindow(string s, string t) {
unordered_map<char, int> need, window;
for(auto c:t)
need[c]++;
int left = 0, right = 0;
int valid = 0;
int start = 0, len = INT_MAX;
while(right < s.size()){
char ch = s[right];
right++;
if(need.count(ch)){
window[ch]++;
if(window[ch] == need[ch])
valid++;
}
while(valid == need.size()){
if(right - left < len){
start = left;
len = right - left;
}
ch = s[left];
left++;
if(need.count(ch)){
if(window[ch] == need[ch])
valid--;
window[ch]--;
}
}
}
return len == INT_MAX ? "" : s.substr(start, len);
}
};