Use sliding window concept to find count of subarrays having k distinct elements .
let ans = 0 , right = 0 , window = 0 ; for ( let left = 0 ; left < n ; left ++ ) { while ( right < n && window < k ) { if ( vid . has ( arr [ right ] ) ) vid . set ( arr [ right ] , vid . get ( arr [ right ] ) + 1 ) ; else vid . set ( arr [ right ] , 1 ) ; if ( vid . get ( arr [ right ] ) == 1 ) window ++ ; right ++ ; }