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
using System ; using System . Collections . Generic ; class GFG { static int cntSubarrays ( int [ ] arr , int N ) { int cntSub = 0 ; int cntUnique = 0 ; Dictionary < int , int > cntFreq = new Dictionary < int , int > ( ) ; for ( int i = 0 ; i < N ; i ++ ) { for ( int j = i ; j < N ; j ++ ) { if ( cntFreq . ContainsKey ( arr [ j ] ) ) { var val = cntFreq [ arr [ j ] ] ; cntFreq . Remove ( arr [ j ] ) ; cntFreq . Add ( arr [ j ] , val + 1 ) ; } else { cntFreq . Add ( arr [ j ] , 1 ) ; } if ( cntFreq [ arr [ j ] ] == 1 ) { cntUnique ++ ; } else if ( cntFreq [ arr [ j ] ] == 2 ) { cntUnique -- ; } if ( cntUnique == 0 ) { cntSub ++ ; } } cntFreq . Clear ( ) ; cntUnique = 0 ; } return cntSub ; } public static void Main ( ) { int [ ] arr = { 1 , 1 , 2 , 2 , 2 } ; int N = arr . Length ; Console . Write ( cntSubarrays ( arr , N ) ) ; } }