Given two sorted arrays, find a pair whose sum is closest to a given sum where the pair consists of elements from each array.

For example,

Input:
 
first[] = { 1, 8, 10, 12 }
second[] = { 2, 4, 9, 15 }
target = 11
 
Output: The closest pair is [1, 9]
 
 
Input:
 
first[] = { 10, 12, 15, 18, 20 }
second[] = { 1, 4, 6, 8 }
target = 22
 
Output: The closest pair is [18, 4]

Practice this problem

1. Brute-Force Approach

A simple solution is to consider all pairs and keep track of the pair closest to the given sum. This approach is demonstrated below in C, Java, and Python:

C


Download  Run Code

Output:

The closest pair is [1, 9]

Java


Download  Run Code

Output:

The closest pair is [1, 9]

Python


Download  Run Code

Output:

The closest pair is (1, 9)

The time complexity of this approach is O(n2) and doesn’t require any extra space, where n is the size of the input.

2. Two-pointer Approach

We can easily solve the problem by maintaining two pointers, i and j, and keeping the search space first[i…] and second[…j]. The first pointer, i, initially points at the beginning of the first array, first, and the second pointer j initially points at the end of the second array, second.

At each iteration of the loop, process the elements present at index i and j and update the closest pair to the current pair (i, j) if the absolute value of (first[i] + second[j] - target) is minimum among all pairs processed.

  • If the sum of the current pair (i, j) is less than target, increment i as an element at index i+1 has more value than the element at index i.
  • If the sum of the current pair (i, j) is more than target, decrement j as an element at index j-1 has less value than the element at index j.

The loop continues if i is less than the first array’s size, and j is more than index 0. This approach is demonstrated below in C, Java, and Python:

C


Download  Run Code

Output:

The closest pair is [1, 9]

Java


Download  Run Code

Output:

The closest pair is [1, 9]

Python


Download  Run Code

Output:

The closest pair is (1, 9)

The time complexity of the above solution is O(n) and doesn’t require any extra space.