Count number of substrings | Practice | GeeksforGeeks

Given a string of lowercase alphabets, count all possible substrings (not necessarily distinct) that have exactly k distinct characters. 

Example 1:
Input:
S = "aba", K = 2
Output:
3
Explanation:
The substrings are:
"ab", "ba" and "aba".

Example 2:
Input: 
S = "abaaca", K = 1
Output:
7
Explanation:
The substrings are:
"a", "b", "a", "aa", "a", "c", "a". 


Your Task:
You don't need to read input or print anything. Your task is to complete the function substrCount() which takes the string S and an integer K as inputs and returns the number of substrings having exactly K distinct characters.

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

Constraints:
1 ≤ |S| ≤ 105
1 ≤ K ≤ 26
-1
tejasbhagat543 months ago
Java
class Solution{   public static boolean isValid(String s,int k)   {       if(s.length()<k)return false;       HashMap<Character ,Integer>map=new HashMap<>();       for(int i=0;i<s.length();i++)       {           char c=s.charAt(i);           if(!(map.containsKey(c)))           {              map.put(c,i);           }                     //return  false;       }        if(map.size()==k)return true;        return false;   }   long substrCount (String s, int k)    {       long ans=0;         for(int i=0;i<s.length();i++)      {          for(int j=i+k;j<=s.length();j++)          {              if(isValid(s.substring(i,j),k))              {                  ans++;                 // System.out.println(s.substring(i,j));              }          }      }      return ans;   }}
0
Sourabh Shah9 months ago
Sourabh Shah
long long int atmost (string s, int k) {    //code here.    if(s.size()==0 || k==0) return 0;    long long int c=0,ans=0,i=0,j=0,n=s.size();    int f[26]={0};    while(j<n){ f[s[j]-'a']++;="" if(f[s[j]-'a']="=1)c++;" while(i<="j" &&="" c="">k){           f[s[i]-'a']--;           if(f[s[i]-'a']==0)c--;           i++;        }        ans+=(j-i+1);        j++;    }    return ans;    }    long long int substrCount (string s, int k) {    //code here.    return atmost(s,k)-atmost(s,k-1);    }
0
Yuvraj Bedi
This comment was deleted.
0
sudarshan maskare10 months ago
sudarshan maskare
Think->window concept->constant space->easy long long int atMostK(string& A, int K) {        long long int i = 0, res = 0;        int count[26]={0};        for (long long int j = 0; j < A.size(); ++j) {            if (!count[A[j]-97]++) K--;            while (K < 0) {                if (!--count[A[i]-97]) K++;                i++;            }            res += j - i + 1;        }        return res;    }    public:        long long int substrCount (string s, int k)        {         return atMostK(s,k)-atMostK(s,k-1);        }
-1
Debjyoti Chattopadhyay10 months ago
Debjyoti Chattopadhyay
class Sol{    long substrCount (String str, int k)    {        long ans=0;        int smap[]=new int[26];        int lmap[]=new int[26];        int e=-1;        int ptrs=0;        int ptrl=0;        char prevs='@';        char prevl='@';        for(int i=0;i<str.length();i++){ while(ptrs<str.length()="" &&="" count(smap)<="k-1){" smap[str.charat(ptrs)-97]++;="" ptrs++;="" }="" if(count(smap)="=k)" smap[str.charat(--ptrs)-97]--;="" while(ptrl<str.length()="" &&="" count(lmap)<="k){" lmap[str.charat(ptrl)-97]++;="" ptrl++;="" }="" if(count(lmap)="=k+1)" lmap[str.charat(--ptrl)-97]--;="" ans+="diff(lmap,smap);" smap[str.charat(i)-97]--;="" lmap[str.charat(i)-97]--;="" }="" return(ans);="" }="" substrcount="" public="" int="" count(int="" arr[]){="" int="" c="0;" for(int="" i="0;i&lt;26;i++){" if(arr[i]="">0)                c++;        }        return(c);    }//count    public int diff(int arr1[],int arr2[]){        int c=0;        for(int i=0;i<26;i++)            c+=(arr1[i]-arr2[i]);        return(c);    }//diff}//SolJAVA Soln
+1
Aiiyan Sinha11 months ago
Aiiyan Sinha
Can anyone tell me why this solution is showing TLE
https://ide.geeksforgeeks.o...
0
Soumya Jha11 months ago
Soumya Jha
@sandeep1103:disqus
Unable to figure out a test case where input String is "hq" and k=1output should be 1, whereas the test case expects it to be 2
attaching the screenshot.
https://uploads.disquscdn.c...
0
aadi1551 year ago
aadi155
don't use unordered_map if getting tle
make it(map) manully :)
0
Debarshi Maitra1 year ago
Debarshi Maitra
O(N) Solution : https://ide.geeksforgeeks.o...
0
Anup1 year ago
Anup
JAVA 0.75s https://ide.geeksforgeeks.o...
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.