Count of index pairs with equal elements in an array | Set 2 | C ++ program for the above approach ; 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 ; Driver Code ; Given array arr [ ] ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countPairs ( int arr [ ] , int n ) { int ans = 0 ; unordered_map < int , int > count ; for ( int i = 0 ; i < n ; i ++ ) { if ( count [ arr [ i ] ] != 0 ) ans += count [ arr [ i ] ] ; count [ arr [ i ] ] ++ ; } return ans ; } int main ( ) { int arr [ ] = { 1 , 2 , 1 , 1 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << countPairs ( arr , N ) ; return 0 ; }