Count subarrays having each distinct element occurring at least twice | C ++ program to implement the above approach ; Function to get the count of subarrays having each element occurring at least twice ; Stores count of subarrays having each distinct element occurring at least twice ; Stores count of unique elements in a subarray ; Store frequency of each element of a subarray ; Traverse the given array ; Count frequency and check conditions for each subarray ; Update frequency ; Check if frequency of arr [ j ] equal to 1 ; Update Count of unique elements ; Update count of unique elements ; If each element of subarray occurs at least twice ; Update cntSub ; Remove all elements from the subarray ; Update cntUnique ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int cntSubarrays ( int arr [ ] , int N ) { int cntSub = 0 ; int cntUnique = 0 ; unordered_map < int , int > cntFreq ; for ( int i = 0 ; i < N ; i ++ ) { for ( int j = i ; j < N ; j ++ ) { cntFreq [ arr [ j ] ] ++ ; if ( cntFreq [ arr [ j ] ] == 1 ) { cntUnique ++ ; } else if ( cntFreq [ arr [ j ] ] == 2 ) { cntUnique -- ; } if ( cntUnique == 0 ) { cntSub ++ ; } } cntFreq . clear ( ) ; cntUnique = 0 ; } return cntSub ; } int main ( ) { int arr [ ] = { 1 , 1 , 2 , 2 , 2 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << cntSubarrays ( arr , N ) ; }