Count subarrays having total distinct elements same as original array | Function to calculate distinct sub - array ; Count distinct elements in whole array ; Reset the container by removing all elements ; Use sliding window concept to find count of subarrays having k distinct elements . ; If window size equals to array distinct element size , then update answer ; Decrease the frequency of previous element for next sliding window ; If frequency is zero then decrease the window size ; Driver code
def countDistictSubarray ( arr , n ) : NEW_LINE INDENT vis = dict ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT vis [ arr [ i ] ] = 1 NEW_LINE DEDENT k = len ( vis ) NEW_LINE vid = dict ( ) NEW_LINE 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 if ( window == k ) : NEW_LINE INDENT ans += ( n - right + 1 ) NEW_LINE DEDENT vid [ arr [ left ] ] -= 1 NEW_LINE if ( vid [ arr [ left ] ] == 0 ) : NEW_LINE INDENT window -= 1 NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT arr = [ 2 , 1 , 3 , 2 , 3 ] NEW_LINE n = len ( arr ) NEW_LINE print ( countDistictSubarray ( arr , n ) ) NEW_LINE