Number of substrings with count of each character as k | C ++ program to count number of substrings with counts of distinct characters as k . ; Returns true if all values in freq [ ] are either 0 or k . ; Returns count of substrings where frequency of every present character is k ; Pick a starting point ; Initialize all frequencies as 0 for this starting point ; One by one pick ending points ; Increment frequency of current char ; If frequency becomes more than k , we can 't have more substrings  starting with i ; If frequency becomes k , then check other frequencies as well . ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX_CHAR = 26 ; bool check ( int freq [ ] , int k ) { for ( int i = 0 ; i < MAX_CHAR ; i ++ ) if ( freq [ i ] && freq [ i ] != k ) return false ; return true ; } int substrings ( string s , int k ) { for ( int i = 0 ; s [ i ] ; i ++ ) { int freq [ MAX_CHAR ] = { 0 } ; for ( int j = i ; s [ j ] ; j ++ ) { int index = s [ j ] - ' a ' ; freq [ index ] ++ ; if ( freq [ index ] > k ) break ; else if ( freq [ index ] == k && check ( freq , k ) == true ) res ++ ; } } return res ; } int main ( ) { string s = " aabbcc " ; int k = 2 ; cout << substrings ( s , k ) << endl ; s = " aabbc " ; k = 2 ; cout << substrings ( s , k ) << endl ; }