Number of substrings with count of each character as k | Java 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
class GFG { static int MAX_CHAR = 26 ; static boolean check ( int freq [ ] , int k ) { for ( int i = 0 ; i < MAX_CHAR ; i ++ ) if ( freq [ i ] != 0 && freq [ i ] != k ) return false ; return true ; } static int substrings ( String s , int k ) { for ( int i = 0 ; i < s . length ( ) ; i ++ ) { int freq [ ] = new int [ MAX_CHAR ] ; for ( int j = i ; j < s . length ( ) ; j ++ ) { int index = s . charAt ( j ) - ' a ' ; freq [ index ] ++ ; if ( freq [ index ] > k ) break ; else if ( freq [ index ] == k && check ( freq , k ) == true ) res ++ ; } } return res ; } public static void main ( String [ ] args ) { String s = " aabbcc " ; int k = 2 ; System . out . println ( substrings ( s , k ) ) ; s = " aabbc " ; k = 2 ; System . out . println ( substrings ( s , k ) ) ; } }