Count of index pairs with equal elements in an array | Set 2 | Function that count the pairs having same elements in the array arr [ ] ; Hash map to keep track of occurences of elements ; Traverse the array arr [ ] ; Check if occurence of arr [ i ] > 0 add count [ arr [ i ] ] to answer ; Return the result ; Given array arr [ ] ; Function call
def countPairs ( arr , n ) : NEW_LINE INDENT ans = 0 NEW_LINE count = { } NEW_LINE for i in range ( n ) : NEW_LINE INDENT if arr [ i ] in count : NEW_LINE INDENT ans += count [ arr [ i ] ] NEW_LINE DEDENT if arr [ i ] in count : NEW_LINE INDENT count [ arr [ i ] ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT count [ arr [ i ] ] = 1 NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT arr = [ 1 , 2 , 1 , 1 ] NEW_LINE N = len ( arr ) NEW_LINE print ( countPairs ( arr , N ) ) NEW_LINE