Find three closest elements from given three sorted arrays
Last Updated :
26 Oct, 2023
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
Explanation: 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
Explanation: 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.
Steps to implement-
- Declared three variables a,b, and c to store final answers
- Initialized a variable “ans” with the Maximum value
- We will store a minimum of max(abs(A[i] – B[j]), abs(B[j] – C[k]), abs(C[k] – A[i])) in “ans” variable
- Run three nested loops where each loop is for each array
- From that loop if max(abs(A[i] – B[j]), abs(B[j] – C[k]), abs(C[k] – A[i])) is less than a minimum of max(abs(A[i] – B[j]), abs(B[j] – C[k]), abs(C[k] – A[i])) present in “ans”
- Then, update “ans” with new max(abs(A[i] – B[j]), abs(B[j] – C[k]), abs(C[k] – A[i])) and that three variable a,b,c with three elements of those arrays
- In the last print value present in a,b,c
Code-
C++
#include<bits/stdc++.h>
using namespace std;
void findClosest( int A[], int B[], int C[], int p, int q, int r)
{
int a,b,c;
int ans=INT_MAX;
for ( int i=0;i<p;i++){
for ( int j=0;j<q;j++){
for ( int k=0;k<r;k++){
int curr=max( abs (A[i]-B[j]), abs (B[j]-C[k]));
int temp=max(curr, abs (C[k]-A[i]));
if (temp<ans){
ans=temp;
a=A[i];
b=B[j];
c=C[k];
}
}
}
}
cout<<a<< " " <<b<< " " <<c<<endl;
}
int 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
import java.util.Arrays;
public class GFG {
public static void findClosest( int [] A, int [] B,
int [] C, int p, int q,
int r)
{
int a = 0 , b = 0 , c = 0 ;
int ans = Integer.MAX_VALUE;
for ( int i = 0 ; i < p; i++) {
for ( int j = 0 ; j < q; j++) {
for ( int k = 0 ; k < r; k++) {
int curr
= Math.max(Math.abs(A[i] - B[j]),
Math.abs(B[j] - C[k]));
int temp = Math.max(
curr, Math.abs(C[k] - A[i]));
if (temp < ans) {
ans = temp;
a = A[i];
b = B[j];
c = C[k];
}
}
}
}
System.out.println(a + " " + b + " " + c);
}
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;
findClosest(A, B, C, p, q, r);
}
}
|
Python3
def findClosest(A, B, C, p, q, r):
a, b, c = None , None , None
ans = float ( 'inf' )
for i in range (p):
for j in range (q):
for k in range (r):
curr = max ( abs (A[i] - B[j]), abs (B[j] - C[k]))
temp = max (curr, abs (C[k] - A[i]))
if temp < ans:
ans = temp
a, b, c = A[i], B[j], C[k]
print (a, b, c)
A = [ 1 , 4 , 10 ]
B = [ 2 , 15 , 20 ]
C = [ 10 , 12 ]
p = len (A)
q = len (B)
r = len (C)
findClosest(A, B, C, p, q, r)
|
C#
using System;
class Program
{
static void FindClosest( int [] A, int [] B, int [] C, int p, int q, int r)
{
int a = 0, b = 0, c = 0;
int ans = int .MaxValue;
for ( int i = 0; i < p; i++)
{
for ( int j = 0; j < q; j++)
{
for ( int k = 0; k < r; k++)
{
int curr = Math.Max(Math.Abs(A[i] - B[j]), Math.Abs(B[j] - C[k]));
int temp = Math.Max(curr, Math.Abs(C[k] - A[i]));
if (temp < ans)
{
ans = temp;
a = A[i];
b = B[j];
c = C[k];
}
}
}
}
Console.WriteLine($ "{a} {b} {c}" );
}
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;
FindClosest(A, B, C, p, q, r);
}
}
|
Javascript
function findClosest(A, B, C, p, q, r)
{
let a,b,c;
let ans = Number.MAX_VALUE;
for (let i=0;i<p;i++){
for (let j=0;j<q;j++){
for (let k=0;k<r;k++){
let curr=Math.max(Math.abs(A[i]-B[j]),Math.abs(B[j]-C[k]));
let temp=Math.max(curr,Math.abs(C[k]-A[i]));
if (temp<ans){
ans=temp;
a=A[i];
b=B[j];
c=C[k];
}
}
}
}
console.log(a+ " " + b+ " " + c);
}
let A = [1, 4, 10];
let B = [2, 15, 20];
let C = [10, 12];
let p = A.length;
let q = B.length;
let r = C.length;
findClosest(A, B, C, p, q, r);
|
Output-
10 15 10
Time complexity :O(N3),because of three nested loops
Auxiliary space: O(1),because no extra space has been used
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++
#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;
int res_i =0, res_j = 0, res_k = 0;
int i=0,j=0,k=0;
while (i < p && j < q && k < r)
{
int minimum = min(A[i], min(B[j], C[k]));
int maximum = max(A[i], max(B[j], C[k]));
if (maximum-minimum < diff)
{
res_i = i, res_j = j, res_k = k;
diff = maximum - minimum;
}
if (diff == 0) break ;
if (A[i] == minimum) i++;
else if (B[j] == minimum) j++;
else k++;
}
cout << A[res_i] << " " << B[res_j] << " " << C[res_k];
}
int 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
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;
int res_i = 0 , res_j = 0 , res_k = 0 ;
int i = 0 , j = 0 , k = 0 ;
while (i < p && j < q && k < r)
{
int minimum = Math.min(A[i],
Math.min(B[j], C[k]));
int maximum = Math.max(A[i],
Math.max(B[j], C[k]));
if (maximum-minimum < diff)
{
res_i = i;
res_j = j;
res_k = k;
diff = maximum - minimum;
}
if (diff == 0 ) break ;
if (A[i] == minimum) i++;
else if (B[j] == minimum) j++;
else k++;
}
System.out.println(A[res_i] + " " +
B[res_j] + " " + C[res_k]);
}
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;
findClosest(A, B, C, p, q, r);
}
}
|
Python3
import sys
def findCloset(A, B, C, p, q, r):
diff = sys.maxsize
res_i = 0
res_j = 0
res_k = 0
i = 0
j = 0
k = 0
while (i < p and j < q and k < r):
minimum = min (A[i], min (B[j], C[k]))
maximum = max (A[i], max (B[j], C[k]));
if maximum - minimum < diff:
res_i = i
res_j = j
res_k = k
diff = maximum - minimum;
if diff = = 0 :
break
if A[i] = = minimum:
i = i + 1
elif B[j] = = minimum:
j = j + 1
else :
k = k + 1
print (A[res_i], " " , B[res_j], " " , C[res_k])
A = [ 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)
|
C#
using System;
class GFG
{
static void findClosest( int []A, int []B,
int []C, int p,
int q, int r)
{
int diff = int .MaxValue;
int res_i = 0,
res_j = 0,
res_k = 0;
int i = 0, j = 0, k = 0;
while (i < p && j < q && k < r)
{
int minimum = Math.Min(A[i],
Math.Min(B[j], C[k]));
int maximum = Math.Max(A[i],
Math.Max(B[j], C[k]));
if (maximum - minimum < diff)
{
res_i = i;
res_j = j;
res_k = k;
diff = maximum - minimum;
}
if (diff == 0) break ;
if (A[i] == minimum) i++;
else if (B[j] == minimum) j++;
else k++;
}
Console.WriteLine(A[res_i] + " " +
B[res_j] + " " +
C[res_k]);
}
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;
findClosest(A, B, C, p, q, r);
}
}
|
Javascript
<script>
function findClosest(A, B, C, p, q, r)
{
var diff = Math.pow(10, 9);
var res_i = 0,
res_j = 0,
res_k = 0;
var i = 0,
j = 0,
k = 0;
while (i < p && j < q && k < r)
{
var minimum = Math.min(A[i], Math.min(B[j], C[k]));
var maximum = Math.max(A[i], Math.max(B[j], C[k]));
if (maximum - minimum < diff)
{
(res_i = i), (res_j = j), (res_k = k);
diff = maximum - minimum;
}
if (diff == 0) break ;
if (A[i] == minimum)
i++;
else if (B[j] == minimum)
j++;
else
k++;
}
document.write(A[res_i] + " " + B[res_j] + " " + C[res_k]);
}
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);
</script>
|
PHP
<?php
function findClosest( $A , $B , $C , $p , $q , $r )
{
$diff = PHP_INT_MAX;
$res_i = 0;
$res_j = 0;
$res_k = 0;
$i = 0;
$j = 0;
$k = 0;
while ( $i < $p && $j < $q && $k < $r )
{
$minimum = min( $A [ $i ], min( $B [ $j ], $C [ $k ]));
$maximum = max( $A [ $i ], max( $B [ $j ], $C [ $k ]));
if ( $maximum - $minimum < $diff )
{
$res_i = $i ; $res_j = $j ; $res_k = $k ;
$diff = $maximum - $minimum ;
}
if ( $diff == 0) break ;
if ( $A [ $i ] == $minimum ) $i ++;
else if ( $B [ $j ] == $minimum ) $j ++;
else $k ++;
}
echo $A [ $res_i ] , " " , $B [ $res_j ],
" " , $C [ $res_k ];
}
$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 );
?>
|
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.
Auxiliary space: O(1) as constant space is required.
Approach 2: Using Binary Search:
Another approach to solve this problem can be to use binary search along with two pointers.
First, sort all the three arrays A, B, and C. Then, we take three pointers, one for each array. For each i, j, k combination, we calculate the maximum difference using the absolute value formula given in the problem. If the current maximum difference is less than the minimum difference found so far, then we update our result.
Next, we move our pointers based on the value of the maximum element among the current i, j, k pointers. We increment the pointer of the array with the smallest maximum element, hoping to find a smaller difference.
The time complexity of this approach will be O(nlogn) due to sorting, where n is the size of the largest array.
Here’s the code for this approach:
C++
#include<bits/stdc++.h>
using namespace std;
void findClosest( int A[], int B[], int C[], int p, int q, int r)
{
sort(A, A+p);
sort(B, B+q);
sort(C, C+r);
int diff = INT_MAX;
int res_i =0, res_j = 0, res_k = 0;
int i=0,j=0,k=0;
while (i < p && j < q && k < r)
{
int minimum = min(A[i], min(B[j], C[k]));
int maximum = max(A[i], max(B[j], C[k]));
int curDiff = abs (maximum - minimum);
if (curDiff < diff)
{
res_i = i, res_j = j, res_k = k;
diff = curDiff;
}
if (A[i] == minimum && A[i] <= B[j] && A[i] <= C[k]) i++;
else if (B[j] == minimum && B[j] <= A[i] && B[j] <= C[k]) j++;
else k++;
}
cout << A[res_i] << " " << B[res_j] << " " << C[res_k];
}
int 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
import java.util.*;
public class Main {
public static void findClosest( int [] A, int [] B, int [] C, int p, int q, int r) {
Arrays.sort(A);
Arrays.sort(B);
Arrays.sort(C);
int diff = Integer.MAX_VALUE;
int res_i = 0 , res_j = 0 , res_k = 0 ;
int i = 0 , j = 0 , k = 0 ;
while (i < p && j < q && k < r) {
int minimum = Math.min(A[i], Math.min(B[j], C[k]));
int maximum = Math.max(A[i], Math.max(B[j], C[k]));
int curDiff = Math.abs(maximum - minimum);
if (curDiff < diff) {
res_i = i;
res_j = j;
res_k = k;
diff = curDiff;
}
if (A[i] == minimum && A[i] <= B[j] && A[i] <= C[k])
i++;
else if (B[j] == minimum && B[j] <= A[i] && B[j] <= C[k])
j++;
else
k++;
}
System.out.println(A[res_i] + " " + B[res_j] + " " + C[res_k]);
}
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;
findClosest(A, B, C, p, q, r);
}
}
|
Python3
import sys
def find_closest(A, B, C):
p, q, r = len (A), len (B), len (C)
A.sort()
B.sort()
C.sort()
diff = sys.maxsize
res_i, res_j, res_k = 0 , 0 , 0
i = j = k = 0
while i < p and j < q and k < r:
minimum = min (A[i], min (B[j], C[k]))
maximum = max (A[i], max (B[j], C[k]))
cur_diff = abs (maximum - minimum)
if cur_diff < diff:
res_i, res_j, res_k = i, j, k
diff = cur_diff
if A[i] = = minimum and A[i] < = B[j] and A[i] < = C[k]:
i + = 1
elif B[j] = = minimum and B[j] < = A[i] and B[j] < = C[k]:
j + = 1
else :
k + = 1
return [A[res_i], B[res_j], C[res_k]]
A = [ 1 , 4 , 10 ]
B = [ 2 , 15 , 20 ]
C = [ 10 , 12 ]
print (find_closest(A, B, C))
|
C#
using System;
public class Program
{
public static int [] FindClosest( int [] A, int [] B, int [] C)
{
int p = A.Length;
int q = B.Length;
int r = C.Length;
Array.Sort(A);
Array.Sort(B);
Array.Sort(C);
int diff = int .MaxValue;
int res_i = 0, res_j = 0, res_k = 0;
int i = 0, j = 0, k = 0;
while (i < p && j < q && k < r)
{
int minimum = Math.Min(A[i], Math.Min(B[j], C[k]));
int maximum = Math.Max(A[i], Math.Max(B[j], C[k]));
int curDiff = Math.Abs(maximum - minimum);
if (curDiff < diff)
{
res_i = i;
res_j = j;
res_k = k;
diff = curDiff;
}
if (A[i] == minimum && A[i] <= B[j] && A[i] <= C[k])
{
i++;
}
else if (B[j] == minimum && B[j] <= A[i] && B[j] <= C[k])
{
j++;
}
else
{
k++;
}
}
return new int [] { A[res_i], B[res_j], C[res_k] };
}
public static void Main()
{
int [] A = { 1, 4, 10 };
int [] B = { 2, 15, 20 };
int [] C = { 10, 12 };
int [] result = FindClosest(A, B, C);
Console.WriteLine( string .Join( " " , result));
}
}
|
Javascript
function find_closest(A, B, C) {
let p = A.length,
q = B.length,
r = C.length;
A.sort((a, b) => a - b);
B.sort((a, b) => a - b);
C.sort((a, b) => a - b);
let diff = Number.MAX_SAFE_INTEGER;
let res_i = 0,
res_j = 0,
res_k = 0;
let i = 0,
j = 0,
k = 0;
while (i < p && j < q && k < r) {
let minimum = Math.min(A[i], Math.min(B[j], C[k]));
let maximum = Math.max(A[i], Math.max(B[j], C[k]));
let cur_diff = Math.abs(maximum - minimum);
if (cur_diff < diff) {
res_i = i;
res_j = j;
res_k = k;
diff = cur_diff;
}
if (A[i] == minimum && A[i] <= B[j] && A[i] <= C[k]) {
i++;
} else if (B[j] == minimum && B[j] <= A[i] && B[j] <= C[k]) {
j++;
} else {
k++;
}
}
return [A[res_i], B[res_j], C[res_k]];
}
let A = [1, 4, 10];
let B = [2, 15, 20];
let C = [10, 12];
console.log(find_closest(A, B, C));
|
OUTPUT:
10 15 10
Time complexity :O(NlogN)
Auxiliary space: O(1) as constant space is required.
//Thanks to Gaurav Ahirwar for suggesting the above solutions.
Please Login to comment...