Count subarrays having each distinct element occurring at least twice | Python3 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
from collections import defaultdict NEW_LINE def cntSubarrays ( arr , N ) : NEW_LINE INDENT cntSub = 0 NEW_LINE cntUnique = 0 NEW_LINE cntFreq = defaultdict ( lambda : 0 ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT for j in range ( i , N ) : NEW_LINE INDENT cntFreq [ arr [ j ] ] += 1 NEW_LINE if ( cntFreq [ arr [ j ] ] == 1 ) : NEW_LINE INDENT cntUnique += 1 NEW_LINE DEDENT elif ( cntFreq [ arr [ j ] ] == 2 ) : NEW_LINE INDENT cntUnique -= 1 NEW_LINE DEDENT if ( cntUnique == 0 ) : NEW_LINE INDENT cntSub += 1 NEW_LINE DEDENT DEDENT cntFreq . clear ( ) NEW_LINE cntUnique = 0 NEW_LINE DEDENT return cntSub NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 1 , 2 , 2 , 2 ] NEW_LINE N = len ( arr ) NEW_LINE print ( cntSubarrays ( arr , N ) ) NEW_LINE DEDENT