Number of substrings with count of each character as k | Javascript 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 ; Initialize result ; 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
let MAX_CHAR = 26 ; function check ( freq , k ) { for ( let i = 0 ; i < MAX_CHAR ; i ++ ) if ( freq [ i ] != 0 && freq [ i ] != k ) return false ; return true ; } function substrings ( s , k ) { let res = 0 ; for ( let i = 0 ; i < s . length ; i ++ ) { let freq = new Array ( MAX_CHAR ) ; for ( let i = 0 ; i < freq . length ; i ++ ) { freq [ i ] = 0 ; } for ( let j = i ; j < s . length ; j ++ ) { let index = s [ j ] . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) ; freq [ index ] ++ ; if ( freq [ index ] > k ) break ; else if ( freq [ index ] == k && check ( freq , k ) == true ) res ++ ; } } return res ; } let s = " " ; let k = 2 ; document . write ( substrings ( s , k ) + " " ) ; s = " " ; k = 2 ; document . write ( substrings ( s , k ) + " " ) ;