Count number of substrings having at least K distinct characters | Function to count number of substrings having atleast k distinct characters ; Stores the size of the string ; Initialize a HashMap ; Stores the start and end indices of sliding window ; Stores the required result ; Iterate while the end pointer is less than n ; Include the character at the end of the window ; Increment end pointer by 1 ; Iterate until count of distinct characters becomes less than K ; Remove the character from the beginning of window ; If its frequency is 0 , remove it from the map ; Update the answer ; Print the result ; Driver Code
function atleastkDistinctChars ( s , k ) { let n = s . length ; let mp = new Map ( ) ; let begin = 0 , end = 0 ; let ans = 0 ; while ( end < n ) { let c = s [ end ] ; if ( mp . has ( c ) ) mp . set ( c , mp . get ( c ) + 1 ) ; else mp . set ( c , 1 ) ; end ++ ; while ( mp . size >= k ) { let pre = s [ begin ] ; mp . set ( pre , mp . get ( pre ) - 1 ) ; if ( mp . get ( pre ) == 0 ) { mp . delete ( pre ) ; } ans += s . length - end + 1 ; begin ++ ; } } document . write ( ans ) ; } let S = " " ; let K = 3 ; atleastkDistinctChars ( S , K ) ;