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
function countPairs ( arr , n ) { let ans = 0 ; let count = new Map ( ) ; for ( let i = 0 ; i < n ; i ++ ) { if ( count . has ( arr [ i ] ) ) { ans += count . get ( arr [ i ] ) ; count . set ( arr [ i ] , count . get ( arr [ i ] ) + 1 ) ; } else { count . set ( arr [ i ] , 1 ) ; } } return ans ; } let arr = [ 1 , 2 , 1 , 1 ] ; let N = arr . length ; document . write ( countPairs ( arr , N ) ) ;