Count subarrays having each distinct element occurring at least twice | 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
function cntSubarrays ( arr , N ) { var cntSub = 0 ; var cntUnique = 0 ; var cntFreq = new Map ( ) ; for ( var i = 0 ; i < N ; i ++ ) { for ( var j = i ; j < N ; j ++ ) { if ( cntFreq . has ( arr [ j ] ) ) cntFreq . set ( arr [ j ] , cntFreq . get ( arr [ j ] ) + 1 ) else cntFreq . set ( arr [ j ] , 1 ) ; if ( cntFreq . get ( arr [ j ] ) == 1 ) { cntUnique ++ ; } else if ( cntFreq . get ( arr [ j ] ) == 2 ) { cntUnique -- ; } if ( cntUnique == 0 ) { cntSub ++ ; } } cntFreq = new Map ( ) ; cntUnique = 0 ; } return cntSub ; } var arr = [ 1 , 1 , 2 , 2 , 2 ] ; var N = arr . length ; document . write ( cntSubarrays ( arr , N ) ) ;