Longest K unique characters substring | Practice | GeeksforGeeks

Given a string you need to print the size of the longest possible substring that has exactly K unique characters. If there is no possible substring then print -1.

Example 1:
Input:
S = "aabacbebebe", K = 3
Output: 7
Explanation: "cbebebe" is the longest 
substring with K distinct characters.

Example 2:
Input: 
S = "aaaa", K = 2
Output: -1
Explanation: There's no substring with K
distinct characters.


Your Task:
You don't need to read input or print anything. Your task is to complete the function longestKSubstr() which takes the string S and an integer K as input and returns the length of the longest substring with exactly K distinct characters. If there is no substring with exactly K distinct characters then return -1.

Expected Time Complexity: O(|S|).
Expected Auxiliary Space: O(1).

Constraints:
1 ≤ |S| ≤ 105
1 ≤ K ≤ 105
0
kushwahdeepu505526 minutes ago
geeks help geeks ...
time 0.05s and space O(1);
cpp easy to understand solutions
vector<int>v(26,0);
int count=0;
int i=0,j=0;
int maxe=-1;
while(i<s.size())
{

 v[s[i]-'a']++;
 if(v[s[i]-'a']==1)
 count++;
 if(count==k)
 {
  maxe=max(maxe,i-j+1);
 }
 if(count>k)
 {
  while(count>k)
  {
   v[s[j]-'a']--;
   if(v[s[j]-'a']==0)
   {
    count--;
   }
   j++;
  }
 }
 i++;
}
return maxe;
 
 
0
19ucs0932 days ago
@admin Please update the expected auxiliary space to O(N) as I think there is no solution for this question that can be done with constant space 
+2
shahabuddinbravo402 days ago
class Solution{ public:   int longestKSubstr(string s, int k) {      int i=0,j=0,mx=-1;      unordered_map<char,int>m;      for(j=0;j<s.size();j++){              m[s[j]]++;              if(m.size()==k){           mx=max((j-i+1),mx);       }              if(m.size()>k){           while(m.size()>k){                       m[s[i]]--;            if(m[s[i]]==0){                m.erase(s[i]);            }                            i++;           }       }   }         return mx;            }};
0
dibyenducse214 days ago
int longestKSubstr(string s, int k) {    int len;    int maxs=-1;    int slen=s.size();    int i=0, j=0;    unordered_map<int, int>mp;
   for(j=0; j<slen; j++)    {       mp[s[j]-'a']++;       if(mp.size()==k)        {            len=j-i+1;            maxs=max(len, maxs);        }       while(mp.size()>k)        {          mp[s[i]-'a']--;           if(mp[s[i]-'a']==0)                  mp.erase(s[i]-'a');           i++;        }    }    return maxs;   }
+2
saurabhjejurkar191 week ago
Java Solution by Legend Aditya Verma|| O(N) TC || O(N) SC
class Solution {
    public int longestkSubstr(String s, int k) {
        // code here
        HashMap<Character,Integer> hm=new HashMap<>();
        
        int i=0;
        int j=0;
        int n=s.length();
        
        int max=0;
        
        while(j<n){
            char ch=s.charAt(j);
            hm.put(ch,hm.getOrDefault(ch,0)+1);
            
            if(hm.size()<k){
                j++;
            }else if(hm.size()==k){
                max=Math.max(j-i+1,max);
                j++;
            }else if(hm.size()>k){
                while(hm.size()>k){
                    hm.put(s.charAt(i),hm.get(s.charAt(i))-1);
                    if(hm.get(s.charAt(i))==0){
                        hm.remove(s.charAt(i));
                    }
                    i++;
                    if(hm.size()==k){
                max=Math.max(j-i+1,max);}
                }
                j++;
            }
        }
        if(max==0) return -1;
        return max;
    }
}
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.
Make sure you are not using ad-blockers.
Disable browser extensions.
We recommend using latest version of your browser for best experience.
Avoid using static/global variables in coding problems as your code is tested 
                                against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases in coding problems 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.