Leaderboard
Showing:
Handle Score
@Ibrahim Nash 6560
@blackshadows 6400
@mb1973 5777
@Quandray 5271
@akhayrutdinov 5111
@saiujwal13083 5074
@kirtidee18 4356
@sanjay05 3762
@mantu_singh 3638
@gfgaccount 3601
@marius_valentin_dragoi 3525
Complete Leaderboard
Find the closest pair from two arrays
Easy Accuracy: 46.06% Submissions: 474 Points: 2

Given two sorted arrays and a number x, find the pair whose sum is closest to x and the pair has an element from each array. In the case of multiple closest pairs return the smallest one.

 

Example 1:

​Input : arr[ ] = {1, 4, 5, 7}
brr[ ] = {10, 20, 30, 40} 
X = 32
Output : 1 30
Explanation:
All the pairs are {1, 10}, {1, 20}, {1, 30}, {1, 40}, {4, 10},
{4, 20}, {4, 30}, {4, 40}, {5, 10}, {5, 20}, {5, 30}, {5, 40},
{7, 10}, {7, 20}, {7, 30}, {7, 40}
The closest pair whose sum is closest to 32 is {1, 30} = 31.
return {1, 30}.
​

Example 2:

Input : arr[ ] = {1, 4, 5, 7}
brr[ ] = {10, 20, 30, 40}
X = 50 
Output :  7 40 

 

Your Task:
This is a function problem. The input is already taken care of by the driver code. You only need to complete the function printClosest() that takes an array (arr), another array (brr), size of array arr (N), size of array brr (M), and return the array of two integers whose sum is closest to X. The driver code takes care of the printing.

Expected Time Complexity: O(N).
Expected Auxiliary Space: O(1).

Constraints:
1 ≤ N, M ≤ 105
1 ≤ A[i], B[i] ≤ 107


 

to report an issue on this page.

Editorial

We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial?

Yes

All Submissions

My Submissions:

Login to access your submissions.

Find the closest pair from two arrays

Output Window