Geeksforgeeks

Error

×

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

Handle | Score |

@anish5256 | 991 |

@vimleshpratapsingh321 | 980 |

@skj7 | 871 |

@akhileshkumar562002 | 862 |

@pradeeppatidar1999 | 840 |

@kanewilliamson123 | 837 |

@pd420786 | 813 |

@infilooop | 800 |

@bunnybug320 | 796 |

@smitabose7826 | 784 |

@virgat | 768 |

Complete Leaderboard |

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 ≤ 10^{5}

1 ≤ A[i], B[i] ≤ 10^{7}

Login to report an issue on this page.

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

YesLoading...

Find the closest pair from two arrays

...