![]() |
VOOZH | about |
Given two arrays a[] and b[], and a positive integer x, find a pair (a[i], b[j]) such that the sum of a[i] and b[j] is closest to x, in other words the absolute difference |a[i] + b[j] - x| is minimized.
Example:
Input: a[] = [1, 4, 5, 7], b[] = [10, 20, 30, 40], x = 32
Output: [1, 30]
Explanation: The pair (1, 30) gives sum 31, which is closest to 32 (minimum difference = 1).
Input: a[] = [1, 4, 5, 7], b[] = [10, 20, 30, 40], x = 50
Output: [7, 40]
Explanation: The pair (7, 40) gives sum 47, which is closest to 50 (minimum difference = 3).
Table of Content
A naive approach is to check all possible pairs formed by taking one element from a[] and one from b[]. For each pair we compute the value |a[i] + b[j] − x| and keep track of the pair that gives the minimum difference.
[7, 40]
The idea is to use the two-pointer technique, taking advantage of the fact that both arrays are sorted. We place one pointer at the beginning of the first array and another at the end of the second array. At each step, we compare the sum of the two elements with
xand move the pointers in the direction that brings the sum closer tox, while updating the minimum difference found so far.
Algorithm:
l = 0, r = m-1) and keep updating the pair with minimum | a[l] + b[r] - x | while traversing. r--, else move l++, until pointers go out of bounds.[7, 30]