Smallest distinct window | Practice | GeeksforGeeks

Given a string 's'. The task is to find the smallest window length that contains all the characters of the given string at least one time.
For eg. A = aabcbcdbca, then the result would be 4 as of the smallest window will be dbca.
 
Example 1:
Input : "AABBBCBBAC"
Output : 3
Explanation : Sub-string -> "BAC"

Input : "aaab"
Output : 2
Explanation : Sub-string -> "ab"
Input : "GEEKSGEEKSFOR"
Output : 8
Explanation : Sub-string -> "GEEKSFOR"
 

Your Task:  
You don't need to read input or print anything. Your task is to complete the function findSubString() which takes the string  S as input and returns the length of the smallest such window of the string.

Expected Time Complexity: O(256.N)
Expected Auxiliary Space: O(256)
 
Constraints:
1 ≤ |S| ≤ 105
String may contain both type of English Alphabets.
+1
bhatshripad181 month ago
Can someone please explain me, why aren't we decreasing counter when shrinking the window,as there might be possibility that we may move to window where certain character is not present in window
+1
aloksinghbais022 months ago
C++ solution having time complexity as O(N*127) and space complexity as O(127) is as follows :- 
 
Execution Time :- 0.2 / 3.2 sec
 
string findSubString(string str){       int n = str.length();       int freq[127] = {0};              int tdc = 0; // total distinct character       for(int i = 0; i < n; i++){           if(freq[str[i]] == 0) tdc++;           freq[str[i]]++;       }              memset(freq,0,sizeof(freq));              int cnt = 0;       int st = 0;       int size = n;       int i = 0, j = 0;       while(j < n){           if(freq[str[j]] == 0) cnt++;           freq[str[j]]++;                      while(cnt == tdc){               if(j-i+1 < size){                   st = i;                   size = j-i+1;               }               freq[str[i]]--;               if(freq[str[i++]] == 0){                   cnt--;               }           }           j++;       }              return (str.substr(st,size));   }
0
parthprajapati972392 months ago
/* Understandable code in c++ */
 
string findSubString(string str)   {              int n = str.size();       vector<int>hash(260,0);              for(int i=0;i<n;i++)       {           hash[str[i]]++;       }              int uniq = 0;       for(int i=0;i<260;i++)       {           if(hash[i] != 0) uniq++;           hash[i] = 0;       }          int start = 0;       //to store latest index of occurance of any character.       unordered_map<char,int>mp;       string ans = "";       int len = n;              for(int i=0;i<n;i++)       {           mp[str[i]] = i;           int mn_start = i;           for(auto it : mp)           {               mn_start = min(mn_start , it.second);           }                  if(mp.size() == uniq)           {               if(len >= (i-mn_start + 1))               {                   len = i-mn_start+1;                   ans = "";                   ans = str.substr(mn_start,len);               }           }       }              return ans;   }
0
manishkumar250319992 months ago
 string findSubString(string str)   {       unordered_map<char,int>mp;       for(int i=0;i<str.length();i++)          mp[str[i]]++;          int size=mp.size();          mp.clear();          int count=0,start=0,sindex=-1,len=INT_MAX;          for(int i=0;i<str.length();i++)          {             mp[str[i]]++;             int count=mp.size();             if(count==size)             {                 while(mp[str[start]]>1)                 {                     if(mp[str[start]]>1)                       mp[str[start]]--;                       start++;                 }                 int len_window=i-start+1;                 if(len_window<len)                 {                     len=len_window;                     sindex=start;                 }             }          }              return str.substr(sindex,len);
0
sankarshansiddhanti6782 months ago
readable c++ code using sliding window technique:
 
string findSubString(string str)   {       unordered_set<int> distinctChars;              for(char c: str)       {           distinctChars.insert(c);       }              int totalDistinctCount = distinctChars.size();       //cout<<totalDistinctCount;              int ans_start,ans_end, win_start, win_end;       ans_start = ans_end = win_start = 0;       win_end = 1;       unordered_map<char,int> frequency;       frequency[str[0]]++;       int curr_dist_count = 1;              int minSizeSoFar = INT_MAX;              while( win_start <= win_end && win_end < str.length() )       {           if( curr_dist_count < totalDistinctCount )           {                if(frequency[str[win_end]] == 0)               {                   curr_dist_count++;               }               frequency[str[win_end]]++;               win_end++;           }           else if( curr_dist_count == totalDistinctCount )           {               int curr_win_size = win_end - win_start;               if( curr_win_size < minSizeSoFar )               {                   ans_start = win_start;                   ans_end = win_end;                   minSizeSoFar = curr_win_size;               }                              if( frequency[str[win_start]] == 1 ) curr_dist_count--;               frequency[str[win_start]]--;               win_start++;           }                      while( curr_dist_count == totalDistinctCount )           {               int curr_win_size = win_end - win_start;               if( curr_win_size < minSizeSoFar )               {                   ans_start = win_start;                   ans_end = win_end;                   minSizeSoFar = curr_win_size;               }                              if( frequency[str[win_start]] == 1 ) curr_dist_count--;               frequency[str[win_start]]--;               win_start++;           }                  }       string smallest_distinct_window = str.substr(ans_start,minSizeSoFar);       return smallest_distinct_window;   }
 
+2
2020010432 months ago
//Easy to understand
string findSubString(string str)   {       int n=str.length();       unordered_map<char,int> m;       for(auto i:str)m[i]++;       int c=m.size();       int ans=-1,len=n;       m.clear();       for(int i=0;i<n;i++){           m[str[i]]=i;           if(m.size()==c){               int mi=n;               for(auto i:m){                   mi=min(mi,i.second);               }               if(ans==-1 || len>(i-mi+1)){                   ans=mi;                   len=i-mi+1;               }           }       }       return str.substr(ans,len);   }
0
codecrackerp3 months ago
class Solution{   public:   string findme(string str,map<int,int>m){       int start=-1,end=-1;       string ans;       for(int i=0;i<str.length();i++){           m[str[i]]--;           if(m[str[i]]==0){               start=i;               break;           }       }       for(int i=str.length()-1;i>=0;i--){           if(m[str[i]]>0){           m[str[i]]--;           }           if(m[str[i]]==0){               end=i;               break;           }       }       for(int i=start;i<=end;i++){           ans.push_back(str[i]);       }       return ans;   }   string findSubString(string str)   {       map<int,int>m;       for(int i=0;i<str.length();i++){           m[str[i]]++;       }       string ans1=findme(str,m);       reverse(str.begin(),str.end());       string ans2=findme(str,m);       if(ans1.length()<=ans2.length()){           return ans1;       }       return ans2;   }};
 
I am not getting why this code is giving TLE if any one of u are able to find the glitch then plz help
0
brajmohanst96613 months ago
 public String findSubString( String str) {       // Your code goes here              int pattern [] = new int[256];              String res = "";              int n = str.length() ,n1 = 0, count = 0 , minlen = Integer.MAX_VALUE , start = 0;       int org[] =new  int[256];              for(int i = 0 ; i < n ; i++ )           if(pattern[str.charAt(i)] == 0)              {     n1++;                   pattern[str.charAt(i)]++;                     }                    for(int i = 0 ; i < n ; i++ ){                      org[str.charAt(i)]++;                      if( org[str.charAt(i)] == pattern[str.charAt(i)])               count++;                      if(count == n1){                                             while(org[str.charAt(start)] > pattern[str.charAt(start)] || pattern[str.charAt(start)] == 0){                   if(org[str.charAt(start)] > pattern[str.charAt(start)])                        org[str.charAt(start)]--;                                                                                                start++;               }                                         if( minlen > i - start + 1){                              minlen = i - start + 1;                              res = str.substring(start , i + 1);           }                          }       }              return res;                                                    }      
+4
gaurabhkumarjha271020013 months ago
       int n= str.length();
       
       unordered_map < char, int > m;
       int i=0, j=0, maxx= INT_MAX;
       string res;
       
       for (int i=0; i< n; i++){
 // only those elements appear only one time.       
             m[str[i]]= 0; 
   
       }
       int cnt=0;
       while (i< n){
           
           if (m[str[i]] == 0)
              cnt ++;
     // expand the window the increase by 1.         
            m[str[i]]+= 1; 
           
            
            if (cnt == m.size()){
                
        while (j < n and m[str[j]] > 1){
    
// shrink the window because duplicate elements                    
                      m[str[j]]--; 
                     
                      j++;
                 }
                 
                 if (maxx > (i-j+1)){
                     
                   maxx= i-j+1;
              res= str.substr (j, i-j+1);
                 }
                 
                 
            }
            i++;
       }
       
         return res;
0
krushimonpara243 months ago
Anyone Help me this code only one character time not work my code.
 
 
class Solution {   public String findSubString( String str) {              HashSet<Character> set = new HashSet<Character>();              for(int i=0;i<str.length();i++){                      set.add(str.charAt(i));       }              int distCounter=set.size();       int start=0;       int startIndex=0;       int counter=0;       int min_length =Integer.MAX_VALUE;              int[] visited = new int[256];              for(int i=0;i<str.length();i++){                      visited[str.charAt(i)-65]++;                      if(visited[str.charAt(i)-65]==1)               counter++;                      if(counter==distCounter){                              while(visited[str.charAt(start)-65]>1){                                      if(visited[str.charAt(start)-65]>1){                       visited[str.charAt(start)-65]--;                       start++;                   }                   int cur_length = i-start+1;                   if(cur_length<min_length){                                              min_length=cur_length;                       startIndex = start;                   }               }           }       }       return str.substring(startIndex,startIndex+min_length);          }}
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.