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 Code
< ? php function binarySearch ( $ arr , $ low , $ high , $ x ) { if ( $ high >= $ low ) { $ mid = $ low + ( $ 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 ) { $ count = 0 ; $ i ; sort ( $ arr ) ; for ( $ i = 0 ; $ i < $ n - 1 ; $ i ++ ) if ( binarySearch ( $ arr , $ i + 1 , $ n - 1 , $ arr [ $ i ] + $ k ) != -1 ) $ count ++ ; return $ count ; } $ arr = array ( 1 , 5 , 3 , 4 , 2 ) ; $ n = count ( $ arr ) ; $ k = 3 ; echo " Count ▁ of ▁ pairs ▁ with ▁ given ▁ diff ▁ is ▁ " , countPairsWithDiffK ( $ arr , $ n , $ k ) ; ? >