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
def binarySearch ( arr , low , high , x ) : NEW_LINE INDENT if ( high >= low ) : NEW_LINE INDENT mid = low + ( high - low ) // 2 NEW_LINE if x == arr [ mid ] : NEW_LINE INDENT return ( mid ) NEW_LINE DEDENT elif ( x > arr [ mid ] ) : NEW_LINE INDENT return binarySearch ( arr , ( mid + 1 ) , high , x ) NEW_LINE DEDENT else : NEW_LINE INDENT return binarySearch ( arr , low , ( mid - 1 ) , x ) NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT def countPairsWithDiffK ( arr , n , k ) : NEW_LINE INDENT count = 0 NEW_LINE arr . sort ( ) NEW_LINE for i in range ( 0 , n - 2 ) : NEW_LINE INDENT if ( binarySearch ( arr , i + 1 , n - 1 , arr [ i ] + k ) != - 1 ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT arr = [ 1 , 5 , 3 , 4 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE k = 3 NEW_LINE print ( " Count ▁ of ▁ pairs ▁ with ▁ given ▁ diff ▁ is ▁ " , countPairsWithDiffK ( arr , n , k ) ) NEW_LINE