Smallest window in a string containing all the characters of another string | Practice | GeeksforGeeks

Given two strings S and P. Find the smallest window in the string S consisting of all the characters(including duplicates) of the string P.  Return "-1" in case there is no such window present. In case there are multiple such windows of same length, return the one with the least starting index. 
Example 1:
Input:
S = "timetopractice"
P = "toc"
Output: 
toprac
Explanation: "toprac" is the smallest
substring in which "toc" can be found.

Example 2:
Input:
S = "zoomlazapzo"
P = "oza"
Output: 
apzo
Explanation: "apzo" is the smallest 
substring in which "oza" can be found.
Your Task:
You don't need to read input or print anything. Your task is to complete the function smallestWindow() which takes two string S and P as input paramters and returns the smallest window in string S having all the characters of the string P. In case there are multiple such windows of same length, return the one with the least starting index. 
Expected Time Complexity: O(|S|)
Expected Auxiliary Space: O(1)
Constraints: 
1 ≤ |S|, |P| ≤ 105
0
tupesanket1999in 3 hours
C++ SLIDING WINDOW
Total Time Taken: 0.21/2.2
    string smallestWindow (string s, string p){
       if(s.size()<p.size())return "-1";
       int req[26]={0};
       int brr[26]={0};
       for(int i=0;i<p.size();i++)
           req[p[i]-'a']++;
       int i=0,j=0;
       int useFull=0;
       int left=INT_MIN,right=INT_MAX;
       while(j<s.size()){
           //aquire
           while(useFull<p.size() && j <s.size()){
               if(req[s[j]-'a']>brr[s[j]-'a']){
                   brr[s[j]-'a']++;
                   useFull++;
               }else{
                   brr[s[j]-'a']++;
               }
               j++;
           }
           if((long long)right-left > j-1-i && useFull==p.size()){
               left =i;
               right=j-1;
           }
           //release
           while(useFull==p.size()){
               if(req[s[i]-'a']<brr[s[i]-'a']){
                   brr[s[i]-'a']--;
               }else{
                   brr[s[i]-'a']--;
                   useFull--;
               }
               i++;
               if(useFull==p.size()){
                      if((long long)right-left > j-1-i){
                       left =i;
                       right=j-1;
                   }
               }
           }
       }
       string st="";
       if(left >=0){
           for(int i=left;i<=right;i++)
               st+=s[i];
       }else{
           st="-1";
       }
       return st;
   }
0
mahesh_phutane1 week ago
Simple java solution using HashMap
class Solution
{
    public static String smallestWindow(String s, String p)
    {
        if(p.length() > s.length()) {
            return "-1";  
        }
        
        Map<Character,Integer> mp = new HashMap<>();  //for String p
        Map<Character,Integer> mp1 = new HashMap<>(); //for String s
        
        for(int i = 0; i < p.length(); ++i) {
            mp.put(p.charAt(i),mp.getOrDefault(p.charAt(i),0)+1);
        }
        
        String ans = "-1";
        int maxlen = Integer.MAX_VALUE; // to get minimum length substring
        int i = 0,j = 0;
        int match = 0;       // to store the count of matched char from string p
        
        while(j<s.length()){
            
            //acquire characters in string s
            while(match<p.length()&& j<s.length()){
                
                mp1.put(s.charAt(j),mp1.getOrDefault(s.charAt(j),0)+1);
                
                if(mp1.get(s.charAt(j))<=mp.getOrDefault(s.charAt(j),0)){
                    match+=1;
                }
                j++;
            }
            
            //release characters in string s to get shortest substring
            
            while(match==p.length() && i<s.length()){
                if(match==p.length()){
                    String res = s.substring(i,j);
                    if(res.length()<maxlen){
                            maxlen = res.length();
                            ans = res;  // store ans
                     }
                }
                
                mp1.put(s.charAt(i),mp1.get(s.charAt(i))-1);
                
                if(mp1.get(s.charAt(i))<mp.getOrDefault(s.charAt(i),Integer.MIN_VALUE)){
                    match-=1;
                }
                
                i+=1;
            }
        }
        return ans;
    }
}
0
rohit250820002 weeks ago
 string smallestWindow (string s, string p)
    {
        if(p.length() > s.length()) {
            return "-1";  
        }
        
        unordered_map<char,int> hash;  
        for(int i = 0; i < p.length(); ++i) {
            hash[p[i]]++;
        }
        int num_of_element = hash.size();   
        
        int i = 0; 
        int j = 0; 
        int min_length = s.length();  
        int start_index = 0;  
        bool found = false;  
        
        
        while(j < s.length())  {
            
            if(hash.find(s[j]) != hash.end()) {
                if(--hash[s[j]] == 0) {
                    num_of_element--;     
                }  
            }
            
            while(num_of_element == 0) { 
                found = true;  
                if(min_length > j - i + 1) {
                    min_length = j - i + 1;  
                    start_index = i;  
                }
                if(hash.find(s[i]) != hash.end()) {
                    if(++hash[s[i]] > 0) {
                        num_of_element++; 
                    }
                }
                i++; 
            }
            
            j++; 
        }
        if(found) {
            return s.substr(start_index, min_length);  
        }
        return "-1"; 
    }
+1
abhishekvishwakarma2872 weeks ago
This is not a medium level question, it is a hard level question
+1
aloksinghbais022 weeks ago
C++ solution having time complexity as O(|S|) and space complexity as O(128) is as follows :- 
 
Execution Time :- 0.19 / 2.2 sec
 
string smallestWindow (string s, string p){       int n = s.length(), m = p.length();              int freq1[128] = {0};       for(char x: p){           freq1[x]++;       }              int freq2[128] = {0};       int st = -1;       int len = n;       int cnt = 0;       int i = 0, j = 0;       while(j < n){           char ch = s[j];           if(freq2[ch] < freq1[ch]) cnt++;           freq2[ch]++;                      while(cnt == m){               if(j-i+1 < len){                   st = i;                   len = j-i+1;               }                              if(freq1[s[i]]) freq2[s[i]]--;               if(freq2[s[i]] < freq1[s[i]]) cnt--;               i++;           }                      j++;       }              if(st == -1) return ("-1");       return s.substr(st,len);   }
0
roytanisha5722 weeks ago
I'm getting TLE even though my solution is O(n) time, (n - length of txt)
can someone point out to me what's going wrong. I'm suspecting some infinite computation or I'm missing some test cases. 
 
Idea for the algorithm: I've used sliding window technique where the window txt[i..j] is considered in every iteration and the window is extended when pattern chars are not contained in the window. and when it is contained, the window is shrunk by bringing i closer to j, all the while checking if the pattern chars are contained in the updated window. 
Please comment if anyone is able to find the error, appreciate all help. Thanks! 
 
//aux function to check if pattern is contained in the txt window.
bool patContained(int ctxt[], int cpat[]){
        
        for(int k=0; k<256; k++){
            if(ctxt[k] < cpat[k])
                return false;
            
        }
        
        return true;
    }


string smallestWindow (string txt, string pat)
    {
        int n = txt.length();
        int m = pat.length();
        
        int res = INT_MAX;
        
        int cpat[256] = {0};
        int ctxt[256] = {0};
        
        for(int i=0; i<m; i++)
            cpat[pat[i]]++;
            
        int i=0, j=0;
        int strt = -1, end = -1;
        
        ctxt[txt[0]]++;
        while(j<n){
            //extend the window(j++)until all chars of pat are included in the window
            
            bool isContained = patContained(ctxt, cpat);
            
            if(!isContained){
                //extend the window 
                
                j++;
                ctxt[txt[j]]++;
            }
            else{
                //all chars of pat are contained, so we'll shrink the window(i++)
                //in attempt to get a smaller window conatined all chars of pat
                
                do{
                    if(res > (j-i+1)){
                        res = (j-i+1);
                        strt = i;
                        end = j;
                    }
                    ctxt[txt[i]]--;
                    i++;
                } while(i<=j && patContained(ctxt, cpat));
                
            }
        }
        
        if(res == INT_MAX)
            return "-1";
        else
            return txt.substr(strt,end-strt+1);
    }
+1
madhukartemba2 weeks ago
JAVA SOLUTION:
class Solution
{
    
    private static boolean allPresent(HashMap<Character, Integer> map)
    {
        for(Map.Entry<Character, Integer> es : map.entrySet())
        {
            if(es.getValue()>0) return false;
        }
        
        
        return true;
    }
    
    //Function to find the smallest window in the string s consisting
    //of all the characters of string p.
    public static String smallestWindow(String s, String p)
    {
        HashMap<Character, Integer> map = new HashMap<>();
        
        for(char ch : p.toCharArray())
        {
            map.put(ch, map.getOrDefault(ch, 0)+1);
        }
        int n = s.length();
        int j=0;
        
        int ans_len = Integer.MAX_VALUE;
        
        int st=-1, en=-1;
        
        for(int i=0; i<n; i++)
        {
            char ch = s.charAt(i);
            
            if(map.containsKey(ch)) map.put(ch, map.get(ch)-1);
            
            if(allPresent(map))
            {
                while(j<i)
                {
                    char ch_rem = s.charAt(j);
                    if(map.containsKey(ch_rem)==false)
                    {
                        j++;
                    }
                    else if(map.get(ch_rem)<0)
                    {
                        map.put(ch_rem, map.get(ch_rem)+1);
                        j++;
                    }
                    else
                    {
                        break;
                    }
                }
                
                int len = i-j;
                
                if(ans_len>len)
                {
                    ans_len = len;
                    st = j;
                    en = i;
                }
                
                
            }
            
        }
        
        if(st==-1 || en==-1) return "-1";
        
        return s.substring(st, en+1);
        
        
        
    }
}
+1
abhishektyagi12633 weeks ago
//Please code it right 
string smallestWindow (string s, string p)   {      unordered_map<char,int> m;      for(int i=0;i<p.size();i++){          m[p[i]]=-1;      }              int currlen=s.size()-1;int minlen=s.size()-1;int start,end,fs,fe,r;       int poi=0;       while(poi<s.size()){           // if we found a character and its a new one;           auto f = m.find(s[poi]);           if(f!=m.end() && m[s[poi]]>-1){               m[s[poi]]=poi;                          }           if(f!=m.end() && m[s[poi]]==-1){               m[s[poi]]=poi;           }                           r=INT_MAX;               for(auto v:m){                   if(v.second>=0){                   r=min(v.second,r);}                   else(r=-1);               }               if(r!=-1){               start=r;end=poi;               currlen=poi-r;                      if(currlen<minlen){minlen=currlen;fs=r;fe=poi;}}                  // }           poi++;       }       // cout<<fs<<" "<<fe<<" ";       for(auto r:m){           if(r.second==-1){return "-1";}           // {cout<<r.first<<" "<<r.second;}       }       string aman="";       for(int i=fs;i<=fe;i++){           aman=aman+s[i];       }       return aman;   }
0
itachinamikaze2213 weeks ago
JAVA   
public static String smallestWindow(String s, String p)   {       HashMap<Character, Integer> map2 =new HashMap<>();       for(int i=0; i<p.length();i++)       {           char ch= p.charAt(i);           map2.put(ch, map2.getOrDefault(ch, 0)+1);       }          int matcount=0;   int i=-1;   int j=-1;   int dmct=p.length();   HashMap<Character, Integer> map1 =new HashMap<>();   String ans="";      while(true)   {//acquire      boolean f1=false, f2=false;   while(i<s.length()-1 && matcount<dmct)   {       i++;       char ch=s.charAt(i);       map1.put(ch, map1.getOrDefault(ch, 0)+1);       if(map1.getOrDefault(ch, 0)<=map2.getOrDefault(ch, 0))       {           matcount++;       }       f1= true;   }   //Collect      while(j<i && matcount==dmct)   {       String pans= s.substring(j+1, i+1);       if(ans.length()==0 || pans.length()< ans.length())           ans=pans;              j++;       char ch= s.charAt(j);              if(map1.get(ch)==1)           map1.remove(ch);       else           map1.put(ch, map1.get(ch)-1);                   if(map1.getOrDefault(ch, 0)<map2.getOrDefault(ch,0))           matcount--;       f2=true;       }      if(f1==false && f2==false)   break;   }   if(ans.length()==0)   return"-1";   else   return ans;}
0
manishmaheshwari81331 month ago
pepcoding solution
class Solution
{
    //Function to find the smallest window in the string s consisting
    //of all the characters of string p.
    public static String smallestWindow(String s, String p)
    {
        
        if(p.length()==1)return  String.valueOf(p.charAt(0)) ;
        
        String ans="";
	        int i=-1;
	        int j=-1;
	        HashMap<Character,Integer> map1=new HashMap<Character,Integer>();
	        HashMap<Character,Integer> map2=new HashMap<Character,Integer>();
	        
	        for(int k=0;k<p.length();k++){
	            char chr=p.charAt(k);
	            map2.put(chr,map2.getOrDefault(chr,0)+1);
	        }

	        
	        int cnt=0;
	        int dscnt=p.length(); 
	            
	            while(true){
	            	boolean f1=false;
	       	        boolean f2=false;
	                
	                while(i<s.length() -1 && cnt<dscnt){
	                    i++;
	                    char chr=s.charAt(i);
	               
	                    map1.put(chr,map1.getOrDefault(chr,0)+1);
	                    if(  map1.get(chr)<=map2.getOrDefault(chr,0)){
	                    	 //System.out.println(chr+" "+map2.getOrDefault(chr,0));
	                        cnt++;
	                    }
	                    
	                    f1=true;
	                }
	                
	                while(j<i && cnt==dscnt ){
	                	
	                    String pans=s.substring(j+1,i+1);
	                    //System.out.println(pans);
	                    if(ans.length()==0 || pans.length()<ans.length()){
	                        ans=pans;  
	                    }
	                    j++;
	                    
	                    char chr=s.charAt(j);
	                    if(map1.get(chr)==1)map1.remove(chr);
	                    else{
	                        map1.put(chr, map1.get(chr)-1);
	                    }
	                    
	                    if( map1.getOrDefault(chr,0)<map2.getOrDefault(chr,0)) {
	                    	cnt--;	
	                    	
	                    }
	                    
	                    f2=true;
	                }
	                
	                if(f1==false && f2==false){
	                    break;
	                }	               
	              
	            }
	            
	            if ( ans.length()==0 )return "-1";
	            
	            return ans;   
    }
}
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.