VOOZH about

URL: https://www.geeksforgeeks.org/dsa/given-two-sorted-arrays-number-x-find-pair-whose-sum-closest-x/

⇱ Closest Pairs Sum in Two Sorted Arrays - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Closest Pairs Sum in Two Sorted Arrays

Last Updated : 11 Apr, 2026

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

[Naive Approach] Using Nested Loops - O(n × m) Time and O(1) Space

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.


Output
[7, 40]

[Expected Approach] - Using Two Pointer - O(n + m) Time and O(1) Space

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 x and move the pointers in the direction that brings the sum closer to x, while updating the minimum difference found so far.

Algorithm:

  • Initialize two pointers (l = 0, r = m-1) and keep updating the pair with minimum | a[l] + b[r] - x | while traversing.
  • If sum > x move r--, else move l++, until pointers go out of bounds.

Output
[7, 30]
Comment
Article Tags: