Given two arrays, A and B, i want to find a number from A and a number from B, such that the absolute difference between the two numbers is the smallest.
Eg
A = 1 2 9
B= 4 5 6
Ans : 2,4 as Math.abs(2-4) =2
Sort the two arrays, then iterate them in parallel: For each item in A
, search the closest item in B
by a linear search. Start the linear search in B
where you stopped for the previous item of A
. Always remember the minimal distance found so far.
The time complexity is O(m log m + n log n) for sorting and O(m + n) for the final search, where m and n are the respective lengths of A
and B
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With