Count pairs from two arrays with difference exceeding K | set 2 | 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
function countPairs ( v1 , v2 , n , m , k ) { let count = 0 ; if ( n <= m ) { v1 . sort ( ) ; for ( let j = 0 ; j < m ; j ++ ) { let index = lowerBound ( v1 , 0 , n , v2 [ j ] - k ) ; count += index ; } } else { v2 . sort ( ) ; for ( let i = 0 ; i < n ; i ++ ) { let index = upperBound ( v2 , 0 , m , v1 [ i ] + k ) ; count += m - index ; } } return count ; } function lowerBound ( a , low , high , element ) { while ( low < high ) { let middle = low + ( high - low ) / 2 ; if ( element > a [ middle ] ) low = middle + 1 ; else high = middle ; } return low ; } function upperBound ( a , low , high , element ) { while ( low < high ) { let middle = low + ( high - low ) / 2 ; if ( a [ middle ] > element ) high = middle ; else low = middle + 1 ; } return low ; } let arr = [ 5 , 9 , 1 , 8 ] ; let brr = [ 10 , 12 , 7 , 4 , 2 , 3 ] ; let K = 3 ; let N = arr . length ; let M = brr . length ; document . write ( countPairs ( arr , brr , N , M , K ) ) ;