Count subarrays having total distinct elements same as original array | C # program Count total number of sub - arrays having total distinct elements same as that original array . ; Method 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 method
using System ; using System . Collections . Generic ; class Test { static int countDistictSubarray ( int [ ] arr , int n ) { Dictionary < int , int > vis = new Dictionary < int , int > ( ) ; for ( int i = 0 ; i < n ; ++ i ) if ( ! vis . ContainsKey ( arr [ i ] ) ) vis . Add ( arr [ i ] , 1 ) ; int k = vis . Count ; vis . Clear ( ) ; int ans = 0 , right = 0 , window = 0 ; for ( int left = 0 ; left < n ; ++ left ) { while ( right < n && window < k ) { if ( vis . ContainsKey ( arr [ right ] ) ) vis [ arr [ right ] ] = vis [ arr [ right ] ] + 1 ; else vis . Add ( arr [ right ] , 1 ) ; if ( vis [ arr [ right ] ] == 1 ) ++ window ; ++ right ; } if ( window == k ) ans += ( n - right + 1 ) ; if ( vis . ContainsKey ( arr [ left ] ) ) vis [ arr [ left ] ] = vis [ arr [ left ] ] - 1 ; if ( vis [ arr [ left ] ] == 0 ) -- window ; } return ans ; } public static void Main ( String [ ] args ) { int [ ] arr = { 2 , 1 , 3 , 2 , 3 } ; Console . WriteLine ( countDistictSubarray ( arr , arr . Length ) ) ; } }