Count all distinct pairs with difference equal to k | Standard binary search function ; Returns count of pairs with difference k in arr [ ] of size n . ; Sort array elements ; Pick a first element point ; Driver program
function binarySearch ( arr , low , high , x ) { if ( high >= low ) { let mid = low + Math . floor ( ( high - low ) / 2 ) ; if ( x == arr [ mid ] ) return mid ; if ( x > arr [ mid ] ) return binarySearch ( arr , ( mid + 1 ) , high , x ) ; else return binarySearch ( arr , low , ( mid - 1 ) , x ) ; } return - 1 ; } function countPairsWithDiffK ( arr , n , k ) { let count = 0 , i ; arr . sort ( ( a , b ) => a - b ) ; for ( i = 0 ; i < n - 1 ; i ++ ) if ( binarySearch ( arr , i + 1 , n - 1 , arr [ i ] + k ) != - 1 ) count ++ ; return count ; } let arr = [ 1 , 5 , 3 , 4 , 2 ] ; let n = arr . length ; let k = 3 ; document . write ( " " + countPairsWithDiffK ( arr , n , k ) ) ;