Count subarrays having each distinct element occurring at least twice | Java 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
import java . util . * ; class GFG { static int cntSubarrays ( int arr [ ] , int N ) { int cntSub = 0 ; int cntUnique = 0 ; Map < Integer , Integer > cntFreq = new HashMap < Integer , Integer > ( ) ; for ( int i = 0 ; i < N ; i ++ ) { for ( int j = i ; j < N ; j ++ ) { cntFreq . put ( arr [ j ] , cntFreq . getOrDefault ( arr [ j ] , 0 ) + 1 ) ; if ( cntFreq . get ( arr [ j ] ) == 1 ) { cntUnique ++ ; } else if ( cntFreq . get ( arr [ j ] ) == 2 ) { cntUnique -- ; } if ( cntUnique == 0 ) { cntSub ++ ; } } cntFreq . clear ( ) ; cntUnique = 0 ; } return cntSub ; } public static void main ( String args [ ] ) { int arr [ ] = { 1 , 1 , 2 , 2 , 2 } ; int N = arr . length ; System . out . println ( cntSubarrays ( arr , N ) ) ; } }