fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. int main()
  5. {
  6. int n;
  7. cin>>n;
  8.  
  9. int k;
  10. cin>>k;
  11.  
  12. string s;
  13. cin>>s;
  14.  
  15. int count = 0; // count the number of substrings having atleast 'k' Distinct characters
  16.  
  17. for(int i=0; i<n; i++)
  18. {
  19. unordered_map<char,int>mp; // I have taken a map which will store its distinct characters and its frequency
  20.  
  21. for(int j=i; j<n; j++) // In every sliding window problem if you re entering into for loop or while(j<n) both are same we have to do some calculations
  22. {
  23. mp[s[j]] = mp[s[j]] + 1; // increment the map frequency
  24.  
  25. // mp.size means frequency of the character we are checking not only the frequency
  26. if(mp.size()>=k)
  27. {
  28. int c = n-j;
  29. count = count + c;
  30. break;
  31.  
  32. }
  33. }
  34. }
  35.  
  36. cout<<count;
  37. }
Success #stdin #stdout 0s 5320KB
stdin
5
3
abcca
stdout
4