Number of substrings with count of each character as k | PHP 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
< ? php $ MAX_CHAR = 26 ; function check ( & $ freq , $ k ) { global $ MAX_CHAR ; for ( $ i = 0 ; $ i < $ MAX_CHAR ; $ i ++ ) if ( $ freq [ $ i ] && $ freq [ $ i ] != $ k ) return false ; return true ; } function substrings ( $ s , $ k ) { global $ MAX_CHAR ; for ( $ i = 0 ; $ i < strlen ( $ s ) ; $ i ++ ) { $ freq = array_fill ( 0 , $ MAX_CHAR , NULL ) ; for ( $ j = $ i ; $ j < strlen ( $ s ) ; $ j ++ ) { $ index = ord ( $ s [ $ j ] ) - ord ( ' a ' ) ; $ freq [ $ index ] ++ ; if ( $ freq [ $ index ] > $ k ) break ; else if ( $ freq [ $ index ] == $ k && check ( $ freq , $ k ) == true ) $ res ++ ; } } return $ res ; } $ s = " aabbcc " ; $ k = 2 ; echo substrings ( $ s , $ k ) . " STRNEWLINE " ; $ s = " aabbc " ; $ k = 2 ; echo substrings ( $ s , $ k ) . " STRNEWLINE " ; ? >