Find three closest elements from given three sorted arrays

24 Sep, 2021
Given three sorted arrays A[], B[] and C[], find 3 elements i, j and k from A, B and C respectively such that max(abs(A[i] – B[j]), abs(B[j] – C[k]), abs(C[k] – A[i])) is minimized. Here abs() indicates absolute value.
Example : 
Input: A[] = {1, 4, 10}
       B[] = {2, 15, 20}
       C[] = {10, 12}
Output: 10 15 10
10 from A, 15 from B and 10 from C

Input: A[] = {20, 24, 100}
       B[] = {2, 19, 22, 79, 800}
       C[] = {10, 12, 23, 24, 119}
Output: 24 22 23
24 from A, 22 from B and 23 from C
We strongly recommend you to minimize your browser and try this yourself first.
A Simple Solution is to run three nested loops to consider all triplets from A, B and C. Compute the value of max(abs(A[i] – B[j]), abs(B[j] – C[k]), abs(C[k] – A[i])) for every triplet and return minimum of all values. Time complexity of this solution is O(n3)
A Better Solution is to use Binary Search. 1) Iterate over all elements of A[],       a) Binary search for element just smaller than or equal to in B[] and C[], and note the difference. 2) Repeat step 1 for B[] and C[]. 3) Return overall minimum.Time complexity of this solution is O(nLogn)
Efficient Solution Let ‘p’ be size of A[], ‘q’ be size of B[] and ‘r’ be size of C[]  
1)   Start with i=0, j=0 and k=0 (Three index variables for A,
                                  B and C respectively)

//  p, q and r are sizes of A[], B[] and C[] respectively.
2)   Do following while i < p and j < q and k < r
    a) Find min and maximum of A[i], B[j] and C[k]
    b) Compute diff = max(X, Y, Z) - min(A[i], B[j], C[k]).
    c) If new result is less than current result, change 
       it to the new result.
    d) Increment the pointer of the array which contains 
       the minimum.
Note that we increment the pointer of the array which has the minimum because our goal is to decrease the difference. Increasing the maximum pointer increases the difference. Increase the second maximum pointer can potentially increase the difference. 
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find 3 elements such that max(abs(A[i]-B[j]), abs(B[j]-// C[k]), abs(C[k]-A[i])) is minimized. #include<bits/stdc++.h>using namespace std; void findClosest(int A[], int B[], int C[], int p, int q, int r){     int diff = INT_MAX;  // Initialize min diff     // Initialize result    int res_i =0, res_j = 0, res_k = 0;     // Traverse arrays    int i=0,j=0,k=0;    while (i < p && j < q && k < r)    {        // Find minimum and maximum of current three elements        int minimum = min(A[i], min(B[j], C[k]));        int maximum = max(A[i], max(B[j], C[k]));         // Update result if current diff is less than the min        // diff so far        if (maximum-minimum < diff)        {             res_i = i, res_j = j, res_k = k;             diff = maximum - minimum;        }         // We can't get less than 0 as values are absolute        if (diff == 0) break;         // Increment index of array with smallest value        if (A[i] == minimum) i++;        else if (B[j] == minimum) j++;        else k++;    }     // Print result    cout << A[res_i] << " " << B[res_j] << " " << C[res_k];} // Driver programint main(){    int A[] = {1, 4, 10};    int B[] = {2, 15, 20};    int C[] = {10, 12};     int p = sizeof A / sizeof A[0];    int q = sizeof B / sizeof B[0];    int r = sizeof C / sizeof C[0];     findClosest(A, B, C, p, q, r);    return 0;}
// Java program to find 3 elements such// that max(abs(A[i]-B[j]), abs(B[j]-C[k]),// abs(C[k]-A[i])) is minimized.import java.io.*; class GFG {         static void findClosest(int A[], int B[], int C[],                                  int p, int q, int r)    {        int diff = Integer.MAX_VALUE; // Initialize min diff             // Initialize result        int res_i =0, res_j = 0, res_k = 0;             // Traverse arrays        int i = 0, j = 0, k = 0;        while (i < p && j < q && k < r)        {            // Find minimum and maximum of current three elements            int minimum = Math.min(A[i],                          Math.min(B[j], C[k]));            int maximum = Math.max(A[i],                          Math.max(B[j], C[k]));                 // Update result if current diff is            // less than the min diff so far            if (maximum-minimum < diff)            {                res_i = i;                res_j = j;                res_k = k;                diff = maximum - minimum;            }                 // We can't get less than 0            // as values are absolute            if (diff == 0) break;                 // Increment index of array            // with smallest value            if (A[i] == minimum) i++;            else if (B[j] == minimum) j++;            else k++;        }             // Print result        System.out.println(A[res_i] + " " +                           B[res_j] + " " + C[res_k]);    }     // Driver code    public static void main (String[] args)    {        int A[] = {1, 4, 10};        int B[] = {2, 15, 20};        int C[] = {10, 12};             int p = A.length;        int q = B.length;        int r = C.length;             // Function calling        findClosest(A, B, C, p, q, r);    }} // This code is contributed by Ajit.
# Python program to find 3 elements such# that max(abs(A[i]-B[j]), abs(B[j]- C[k]),# abs(C[k]-A[i])) is minimized.import sys def findCloset(A, B, C, p, q, r):     # Initialize min diff    diff = sys.maxsize     res_i = 0    res_j = 0    res_k = 0     # Traverse Array    i = 0    j = 0    k = 0    while(i < p and j < q and k < r):         # Find minimum and maximum of        # current three elements        minimum = min(A[i], min(B[j], C[k]))        maximum = max(A[i], max(B[j], C[k]));         # Update result if current diff is        # less than the min diff so far        if maximum-minimum < diff:            res_i = i            res_j = j            res_k = k            diff = maximum - minimum;         # We can 't get less than 0 as        # values are absolute        if diff == 0:            break          # Increment index of array with        # smallest value        if A[i] == minimum:            i = i+1        elif B[j] == minimum:            j = j+1        else:            k = k+1     # Print result    print(A[res_i], " ", B[res_j], " ", C[res_k]) # Driver ProgramA = [1, 4, 10]B = [2, 15, 20]C = [10, 12] p = len(A)q = len(B)r = len(C) findCloset(A,B,C,p,q,r) # This code is contributed by Shrikant13.
// C# program to find 3 elements// such that max(abs(A[i]-B[j]),// abs(B[j]-C[k]), abs(C[k]-A[i]))// is minimized.using System; class GFG{    static void findClosest(int []A, int []B,                            int []C, int p,                            int q, int r)    {        // Initialize min diff        int diff = int.MaxValue;             // Initialize result        int res_i = 0,            res_j = 0,            res_k = 0;             // Traverse arrays        int i = 0, j = 0, k = 0;        while (i < p && j < q && k < r)        {            // Find minimum and maximum            // of current three elements            int minimum = Math.Min(A[i],                          Math.Min(B[j], C[k]));            int maximum = Math.Max(A[i],                          Math.Max(B[j], C[k]));                 // Update result if current            // diff is less than the min            // diff so far            if (maximum - minimum < diff)            {                res_i = i;                res_j = j;                res_k = k;                diff = maximum - minimum;            }                 // We can't get less than 0            // as values are absolute            if (diff == 0) break;                 // Increment index of array            // with smallest value            if (A[i] == minimum) i++;            else if (B[j] == minimum) j++;            else k++;        }             // Print result        Console.WriteLine(A[res_i] + " " +                          B[res_j] + " " +                          C[res_k]);    }     // Driver code    public static void Main ()    {        int []A = {1, 4, 10};        int []B = {2, 15, 20};        int []C = {10, 12};             int p = A.Length;        int q = B.Length;        int r = C.Length;             // Function calling        findClosest(A, B, C, p, q, r);    }} // This code is contributed// by anuj_67.
<?php// PHP program to find 3 elements such// that max(abs(A[i]-B[j]), abs(B[j]-// C[k]), abs(C[k]-A[i])) is minimized. function findClosest($A, $B, $C, $p, $q, $r){     $diff = PHP_INT_MAX; // Initialize min diff     // Initialize result    $res_i = 0;    $res_j = 0;    $res_k = 0;     // Traverse arrays    $i = 0;    $j = 0;    $k = 0;    while ($i < $p && $j < $q && $k < $r)    {        // Find minimum and maximum of        // current three elements        $minimum = min($A[$i], min($B[$j], $C[$k]));        $maximum = max($A[$i], max($B[$j], $C[$k]));         // Update result if current diff is        // less than the min diff so far        if ($maximum-$minimum < $diff)        {            $res_i = $i; $res_j = $j; $res_k = $k;            $diff = $maximum - $minimum;        }         // We can't get less than 0 as        // values are absolute        if ($diff == 0) break;         // Increment index of array with        // smallest value        if ($A[$i] == $minimum) $i++;        else if ($B[$j] == $minimum) $j++;        else $k++;    }     // Print result    echo $A[$res_i] , " ", $B[$res_j],                      " ", $C[$res_k];} // Driver Code$A = array(1, 4, 10);$B = array(2, 15, 20);$C = array(10, 12); $p = sizeof($A);$q = sizeof($B);$r = sizeof($C); findClosest($A, $B, $C, $p, $q, $r); // This code is contributed by Sach_Code?>
<script>     // JavaScript program to find 3 elements     // such that max(abs(A[i]-B[j]), abs(B[j]-     // C[k]), abs(C[k]-A[i])) is minimized.      function findClosest(A, B, C, p, q, r)     {       var diff = Math.pow(10, 9); // Initialize min diff        // Initialize result       var res_i = 0,         res_j = 0,         res_k = 0;        // Traverse arrays       var i = 0,         j = 0,         k = 0;       while (i < p && j < q && k < r)       {                 // Find minimum and maximum of current three elements         var minimum = Math.min(A[i], Math.min(B[j], C[k]));         var maximum = Math.max(A[i], Math.max(B[j], C[k]));          // Update result if current diff is less than the min         // diff so far         if (maximum - minimum < diff)         {           (res_i = i), (res_j = j), (res_k = k);           diff = maximum - minimum;         }          // We can't get less than 0 as values are absolute         if (diff == 0) break;          // Increment index of array with smallest value         if (A[i] == minimum)             i++;         else if (B[j] == minimum)             j++;         else             k++;       }        // Print result       document.write(A[res_i] + " " + B[res_j] + " " + C[res_k]);     }      // Driver program     var A = [1, 4, 10];     var B = [2, 15, 20];     var C = [10, 12];      var p = A.length;     var q = B.length;     var r = C.length;      findClosest(A, B, C, p, q, r);           // This code is contributed by rdtank.   </script>
Output: 
10 15 10
Time complexity of this solution is O(p + q + r) where p, q and r are sizes of A[], B[] and C[] respectively.Thanks to Gaurav Ahirwar for suggesting the above solutions.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
shrikanth13
jit_t
vt_m
Sach_Code
paperba1l
rdtank
anantsingh2
sweetyty
Searching
Searching
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Search, insert and delete in an unsorted array
Median of two sorted arrays of different sizes
Program to find largest element in an array
k largest(or smallest) elements in an array
Two Pointers Technique
Given an array of size n and a number k, find all elements that appear more than n/k times
Find the missing and repeating number
Search, insert and delete in a sorted array
Find the index of an array element in Java
Count number of occurrences (or frequency) in a sorted array