Count pairs from two arrays with difference exceeding K | set 2 | Python3 program for the above approach ; Function to count pairs that satisfy the given conditions ; Stores the count of pairs ; If v1 [ ] is smaller than v2 [ ] ; Sort the array v1 [ ] ; Traverse the array v2 [ ] ; Returns the address of the first number which is >= v2 [ j ] - k ; Increase the count by all numbers less than v2 [ j ] - k ; Otherwise ; Sort the array v2 [ ] ; Traverse the array v1 [ ] ; Returns the address of the first number which is > v1 [ i ] + k ; Increase the count by all numbers greater than v1 [ i ] + k ; Return the total count of pairs ; Driver Code
from bisect import bisect_left , bisect_right NEW_LINE def countPairs ( v1 , v2 , n , m , k ) : NEW_LINE INDENT count = 0 NEW_LINE if ( n <= m ) : NEW_LINE INDENT v1 = sorted ( v1 ) NEW_LINE for j in range ( m ) : NEW_LINE INDENT index = bisect_left ( v1 , v2 [ j ] - k ) NEW_LINE count += index NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT v2 = sorted ( v2 ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT index = bisect_right ( v2 , v1 [ i ] + k ) NEW_LINE count += m - index NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 5 , 9 , 1 , 8 ] NEW_LINE brr = [ 10 , 12 , 7 , 4 , 2 , 3 ] NEW_LINE K = 3 NEW_LINE N = len ( arr ) NEW_LINE M = len ( brr ) NEW_LINE print ( countPairs ( arr , brr , N , M , K ) ) NEW_LINE DEDENT