Count substrings with each character occurring at most k times | Javascript program to count number of substrings in which each character has count less than or equal to k . ; variable to store count of substrings . ; array to store count of each character . ; increment character count ; check only the count of current character because only the count of this character is changed . The ending point is incremented to current position only if all other characters have count at most k and hence their count is not checked . If count is less than k , then increase ans by 1. ; if count is less than k , then break as subsequent substrings for this starting point will also have count greater than k and hence are reduntant to check . ; return the final count of substrings . ; Driver code
function findSubstrings ( s , k ) { var ans = 0 ; var cnt = Array ( 26 ) ; var i , j , n = s . length ; for ( i = 0 ; i < n ; i ++ ) { cnt = Array ( 26 ) . fill ( 0 ) ; for ( j = i ; j < n ; j ++ ) { cnt [ ( s [ j ] . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) ) ] ++ ; if ( cnt [ ( s [ j ] . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) ) ] <= k ) ans ++ ; else break ; } } return ans ; } var S = " " ; var k = 2 ; document . write ( findSubstrings ( S , k ) ) ;