VOOZH about

URL: https://www.geeksforgeeks.org/dsa/smallest-difference-pair-values-two-unsorted-arrays/

⇱ Smallest Difference pair of values between two unsorted Arrays - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Smallest Difference pair of values between two unsorted Arrays

Last Updated : 23 Jul, 2025

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:


Output
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: 

  • A: {1, 2, 11, 15} 
  • B: {4, 12, 19, 23, 127, 235} 
  1. Suppose a pointer a points to the beginning of A and a pointer b points to the beginning of B. The current difference between a and b is 3. Store this as the min. 
  2. How can we (potentially) make this difference smaller? Well, the value at b is bigger than the value at a, so moving b will only make the difference larger. Therefore, we want to move a. 
  3. Now a points to 2 and b (still) points to 4. This difference is 2, so we should update min. Move a, since it is smaller. 
  4. Now a points to 11 and b points to 4. Move b. 
  5. Now a points to 11 and b points to 12. Update min to 1. Move b. And so on. 

Below is the implementation of the idea. 


Output
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.  

Comment
Article Tags:
Article Tags: