VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-three-closest-elements-from-given-three-sorted-arrays/

⇱ Closest elements from Three Sorted Arrays - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Closest elements from Three Sorted Arrays

Last Updated : 24 May, 2026

Given three sorted arrays a[], b[] and c[], find the minimum value of max(abs(a[i] – b[j]), abs(b[j] – c[k]), abs(c[k] – a[i])). Here i, j and k are indexes in arrays a[], b[] and c[] respectively and abs() indicates absolute value.

Examples:

Input: a[] = [1, 4, 10], b[] = [2, 15, 20], c[] = [10, 12]
Output: 5
Explanation: We take 10 from a, 15 from b and 10 from c, so max(abs(10-15),abs(15-12),abs(10-10))is 5

Input: a[] = [20, 24, 100], b[] = [2, 19, 22, 79, 800], c[] = [10, 12, 23, 24, 119]
Output: 2
Explanation: We take 24 from a, 22 from b and 24 from c. So max(abs(24-22), abs(24-22), abs(24-24))) is 2.

[Naive Approach] Checking Each Triplet - O(n1 * n2 * n3) Time and O(1) Space

The simplest approach is to try every possible combination of one element from each array. For each combination, we calculate the three differences between the chosen elements and take the maximum of these differences. Among all combinations, the one that gives the smallest maximum difference is the answer, and the corresponding elements from the arrays are the triplet we choose.


Output
5

Time Complexity: O(n1 * n2 * n3)
Auxiliary Space: O(1)

[Expected Approach] Using Three Pointers - O(n1 + n2 + n3) Time and O(1) Space

The problem can be reformulated as finding the triplet (a[i], b[j], c[k]) that minimizes the difference between the maximum and minimum elements among the three. Since the arrays are sorted, we can use a three pointer approach.

The idea is to use three pointers starting from the beginning of the three sorted arrays. At every step, the current elements form a triplet. We calculate the minimum and maximum among these three elements and try to minimize their difference. Since the arrays are sorted, the best way to reduce the range is to move the pointer pointing to the smallest element, because increasing the minimum value may help in reducing the difference in the next steps.

We continue this process as long as all three pointers remain within their arrays. During the traversal, we keep track of the smallest max - min encountered and the corresponding triplet. At the end, the triplet with the minimum difference is returned as the answer.


Output
5

Time Complexity: O(n1 + n2 + n3)
Auxiliary Space: O(1)

Comment
Article Tags:
Article Tags: