Count of index pairs with equal elements in an array | Set 2 | C ++ program for the above approach ; Function that counts the pair in the array arr [ ] ; Sort the array ; Initialize two pointers ; Add all valid pairs to answer ; Return the answer ; 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 ; sort ( arr , arr + n ) ; int left = 0 , right = 1 ; while ( right < n ) { if ( arr [ left ] == arr [ right ] ) ans += right - left ; else left = right ; right ++ ; } return ans ; } int main ( ) { int arr [ ] = { 2 , 2 , 3 , 2 , 3 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << countPairs ( arr , N ) ; return 0 ; }