Use sliding window concept to find count of subarrays having k distinct elements .
ans = 0 NEW_LINE right = 0 NEW_LINE window = 0 NEW_LINE for left in range ( n ) : NEW_LINE INDENT while ( right < n and window < k ) : NEW_LINE INDENT if arr [ right ] in vid . keys ( ) : NEW_LINE INDENT vid [ arr [ right ] ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT vid [ arr [ right ] ] = 1 NEW_LINE DEDENT if ( vid [ arr [ right ] ] == 1 ) : NEW_LINE INDENT window += 1 NEW_LINE DEDENT right += 1 NEW_LINE DEDENT DEDENT