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 . ; 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countDistictSubarray ( int arr [ ] , int n ) { unordered_map < int , int > vis ; for ( int i = 0 ; i < n ; ++ i ) vis [ arr [ i ] ] = 1 ; int k = vis . size ( ) ; vis . clear ( ) ; 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 ; } if ( window == k ) ans += ( n - right + 1 ) ; -- vis [ arr [ left ] ] ; if ( vis [ arr [ left ] ] == 0 ) -- window ; } return ans ; } int main ( ) { int arr [ ] = { 2 , 1 , 3 , 2 , 3 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << countDistictSubarray ( arr , n ) << " n " ; return 0 ; }