Untitled
class Solution { public: string minWindow(string s, string t) { if(t=="") return ""; int n=s.size(); unordered_map<char,int>mt; unordered_map<char,int>window; int need=t.size(),have=0,res=INT_MAX; for(char c:t) mt[c]++; int l=0,r=0; pair<int,int>ind={-1,-1}; // mt contains all the counts of characters needed, need has the no of characters needed while(r<n){ char ch=s[r]; window[ch]++;//map window has count of characters in current window if(mt.find(ch)!=mt.end() && window[ch]<=mt[ch]) have++;//current character is needed and our current window has less count than needed then we increment have , we dotn increment have for duplicates while(have==need){ //moving the left pointer// improving out answer if(r-l+1 <res){ res=r-l+1; ind={l,r-l+1}; } char left=s[l]; window[left]--; if(mt.find(left)!=mt.end() && window[left] < mt[left]) have--; l++; } r++; } if(ind.first==-1) return ""; return s.substr(ind.first,ind.second); } };
Leave a Comment