Count of index pairs with equal elements in an array | Set 2 | Function that counts the pair in the array arr [ ] ; Sort the array ; Initialize two pointers ; Add all valid pairs to answer ; Return the answer ; Given array [ ] arr ; Function call
function countPairs ( arr , n ) { let ans = 0 ; arr . sort ( function ( a , b ) { return a - b } ) ; let left = 0 , right = 1 ; while ( right < n ) { if ( arr [ left ] == arr [ right ] ) ans += right - left ; else left = right ; right ++ ; } return ans ; } let arr = [ 2 , 2 , 3 , 2 , 3 ] ; let N = arr . length ; document . write ( countPairs ( arr , N ) ) ;