Count pairs ( i , j ) from an array such that i < j and arr [ j ] | Function to count the number of pairs ( i , j ) such that i < j and arr [ i ] - arr [ j ] = X * ( j - i ) ; Stores the count of all such pairs that satisfies the condition . ; Stores count of distinct values of arr [ i ] - x * i ; Iterate over the Map ; Increase count of pairs ; Print the count of such pairs ; Driver Code
function countPairs ( arr , n , x ) { let count = 0 ; let mp = new Map ( ) ; for ( let i = 0 ; i < n ; i ++ ) { if ( mp . has ( arr [ i ] - x * i ) ) { mp . set ( arr [ i ] - x * i , mp . get ( arr [ i ] - x * i ) + 1 ) } else { mp . set ( arr [ i ] - x * i , 1 ) } } for ( let x of mp ) { let n = x [ 1 ] ; count += Math . floor ( ( n * ( n - 1 ) ) / 2 ) ; } document . write ( count ) ; } let n = 6 , x = 3 ; let arr = [ 5 , 4 , 8 , 11 , 13 , 16 ] ; countPairs ( arr , n , x ) ;