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