![]() |
VOOZH | about |
Given two arrays of integers, compute the pair of values (one value in each array) with the smallest (non-negative) difference. Return the difference.
Examples :
Input : A[] = {1, 3, 15, 11, 2}
B[] = {23, 127, 235, 19, 8}
Output : 3
That is, the pair (11, 8)
Input : A[] = {10, 5, 40}
B[] = {50, 90, 80}
Output : 10
That is, the pair (40, 50)
Brute Force Approach:
The brute force approach to solve this problem involves comparing each pair of values, one from each array, and calculating their absolute difference. We then keep track of the smallest absolute difference found so far and return it at the end.
Below is the implementation of the above approach:
1
Time Complexity: O(N^2)
Auxiliary Space: O(1)
A better solution is to sort the arrays. Once the arrays are sorted, we can find the minimum difference by iterating through the arrays using the approach discussed in below post.
Find the closest pair from two sorted arrays
Consider the following two arrays:
Below is the implementation of the idea.
1
Time Complexity: O(m log m + n log n)
This algorithm takes O(m log m + n log n) time to sort and O(m + n) time to find the minimum difference. Therefore, the overall runtime is O(m log m + n log n).
Auxiliary Space:O(1)
This article is contributed by Mr. Somesh Awasthi.