Count the pairs in an array such that the difference between them and their indices is equal | Function to return the count of all valid pairs ; To store the frequencies of ( arr [ i ] - i ) ; To store the required count ; If cnt is the number of elements whose difference with their index is same then ( ( cnt * ( cnt - 1 ) ) / 2 ) such pairs are possible ; Driver code
function countPairs ( arr , n ) { var map = { } ; for ( var i = 0 ; i < n ; i ++ ) map [ arr [ i ] - i ] = 0 ; for ( var i = 0 ; i < n ; i ++ ) map [ arr [ i ] - i ] ++ ; var res = 0 ; for ( const [ key , value ] of Object . entries ( map ) ) { var cnt = value ; res += ( cnt * ( cnt - 1 ) ) / 2 ; } return res ; } var arr = [ 1 , 5 , 6 , 7 , 9 ] ; var n = arr . length ; document . write ( countPairs ( arr , n ) ) ;