Count pairs from two arrays with difference exceeding K | Function to count pairs that satisfy the given conditions ; Stores index of the left pointer . ; Stores index of the right pointer ; Stores count of total pairs that satisfy the conditions ; Sort arr [ ] array ; Sort brr [ ] array ; Traverse both the array and count then pairs ; If the value of ( brr [ j ] - arr [ i ] ) exceeds K ; Update cntPairs ; Update ; Update j ; Driver Code
function count_pairs ( arr , brr , N , M , K ) { let i = 0 ; let j = 0 ; let cntPairs = 0 ; ( arr ) . sort ( function ( a , b ) { return a - b ; } ) ; ( brr ) . sort ( function ( a , b ) { return a - b ; } ) ; while ( i < N && j < M ) { if ( brr [ j ] - arr [ i ] > K ) { cntPairs += ( M - j ) ; i ++ ; } else { j ++ ; } } return cntPairs ; } 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 ( count_pairs ( arr , brr , N , M , K ) ) ;