Count number of substrings with exactly k distinct characters | Function to count number of substrings with exactly k unique characters ; Initialize result ; To store count of characters from ' a ' to ' z ' ; Consider all substrings beginning with str [ i ] ; Consider all substrings between str [ i . . j ] ; If this is a new character for this substring , increment dist_count . ; Increment count of current character ; If distinct character count becomes k , then increment result . ; Driver Program
function countkDist ( str , k ) { var res = 0 ; var n = str . length ; var cnt = Array . from ( { length : 26 } , ( _ , i ) => 0 ) ; for ( i = 0 ; i < n ; i ++ ) { var dist_count = 0 ; for ( j = i ; j < n ; j ++ ) { if ( cnt [ str . charAt ( j ) . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) ] == 0 ) dist_count ++ ; cnt [ str . charAt ( j ) . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) ] ++ ; if ( dist_count == k ) res ++ ; } } return res ; } var ch = " " ; var k = 3 ; document . write ( " " + k + " " + countkDist ( ch , k ) ) ;