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
[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.
#include <iostream>
#include <vector>
#include <climits>
#include <cmath>
using namespace std;
// Function to find the closest pair
pair<int, int> closestPair(vector<int>& a, vector<int>& b, int x) {
int minDiff = INT_MAX;
pair<int, int> res;
// Traverse all pairs
for (int i = 0; i < a.size(); i++) {
for (int j = 0; j < b.size(); j++) {
int diff = abs(a[i] + b[j] - x);
if (diff < minDiff) {
minDiff = diff;
res = {a[i], b[j]};
}
}
}
return res;
}
int main() {
vector<int> a = {1, 4, 5, 7};
vector<int> b = {10, 20, 30, 40};
int x = 50;
pair<int, int> ans = closestPair(a, b, x);
cout << "[" << ans.first << ", " << ans.second << "]";
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <math.h>
// Function to find the closest pair
typedef struct { int first; int second; } pair;
pair closestPair(int* a, int* b, int aSize, int bSize, int x) {
int minDiff = INT_MAX;
pair res;
// Traverse all pairs
for (int i = 0; i < aSize; i++) {
for (int j = 0; j < bSize; j++) {
int diff = abs(a[i] + b[j] - x);
if (diff < minDiff) {
minDiff = diff;
res.first = a[i];
res.second = b[j];
}
}
}
return res;
}
int main() {
int a[] = {1, 4, 5, 7};
int b[] = {10, 20, 30, 40};
int x = 50;
int aSize = sizeof(a) / sizeof(a[0]);
int bSize = sizeof(b) / sizeof(b[0]);
pair ans = closestPair(a, b, aSize, bSize, x);
printf("[%d, %d]", ans.first, ans.second);
return 0;
}
import java.util.Arrays;
// Function to find the closest pair
class Pair {
int first, second;
Pair(int first, int second) {
this.first = first;
this.second = second;
}
}
public class Main {
public static Pair closestPair(int[] a, int[] b, int x) {
int minDiff = Integer.MAX_VALUE;
Pair res = new Pair(0, 0);
// Traverse all pairs
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < b.length; j++) {
int diff = Math.abs(a[i] + b[j] - x);
if (diff < minDiff) {
minDiff = diff;
res = new Pair(a[i], b[j]);
}
}
}
return res;
}
public static void main(String[] args) {
int[] a = {1, 4, 5, 7};
int[] b = {10, 20, 30, 40};
int x = 50;
Pair ans = closestPair(a, b, x);
System.out.println("[" + ans.first + ", " + ans.second + "]");
}
}
import sys
from typing import Tuple
# Function to find the closest pair
def closestPair(a: list, b: list, x: int) -> Tuple[int, int]:
minDiff = sys.maxsize
res = (0, 0)
# Traverse all pairs
for i in range(len(a)):
for j in range(len(b)):
diff = abs(a[i] + b[j] - x)
if diff < minDiff:
minDiff = diff
res = (a[i], b[j])
return res
if __name__ == '__main__':
a = [1, 4, 5, 7]
b = [10, 20, 30, 40]
x = 50
ans = closestPair(a, b, x)
print(f'[{ans[0]}, {ans[1]}]')
using System;
// Function to find the closest pair
public class Pair {
public int First { get; set; }
public int Second { get; set; }
public Pair(int first, int second) {
First = first;
Second = second;
}
}
public class Program {
public static Pair ClosestPair(int[] a, int[] b, int x) {
int minDiff = int.MaxValue;
Pair res = new Pair(0, 0);
// Traverse all pairs
for (int i = 0; i < a.Length; i++) {
for (int j = 0; j < b.Length; j++) {
int diff = Math.Abs(a[i] + b[j] - x);
if (diff < minDiff) {
minDiff = diff;
res = new Pair(a[i], b[j]);
}
}
}
return res;
}
public static void Main(string[] args) {
int[] a = {1, 4, 5, 7};
int[] b = {10, 20, 30, 40};
int x = 50;
Pair ans = ClosestPair(a, b, x);
Console.WriteLine("[" + ans.First + ", " + ans.Second + "]");
}
}
function closestPair(a, b, x) {
let minDiff = Number.MAX_SAFE_INTEGER;
let res = { first: 0, second: 0 };
// Traverse all pairs
for (let i = 0; i < a.length; i++) {
for (let j = 0; j < b.length; j++) {
let diff = Math.abs(a[i] + b[j] - x);
if (diff < minDiff) {
minDiff = diff;
res.first = a[i];
res.second = b[j];
}
}
}
return res;
}
let a = [1, 4, 5, 7];
let b = [10, 20, 30, 40];
let x = 50;
let ans = closestPair(a, b, x);
console.log(`[${ans.first}, ${ans.second}]`);
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
xand move the pointers in the direction that brings the sum closer tox, 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 movel++, until pointers go out of bounds.
#include <iostream>
#include <vector>
#include <climits>
#include <cmath>
using namespace std;
vector<int> findClosestPair(vector<int> &a, vector<int> &b, int x)
{
int l = 0, r = b.size() - 1;
int diff = INT_MAX;
vector<int> result(2);
// Two pointer traversal
while (l < a.size() && r >= 0)
{
int sum = a[l] + b[r];
int currDiff = abs(sum - x);
// Update result if better pair found
if (currDiff < diff)
{
diff = currDiff;
result[0] = a[l];
result[1] = b[r];
}
// Move pointers
if (sum > x)
r--;
else
l++;
}
return result;
}
int main()
{
vector<int> a = {1, 4, 5, 7};
vector<int> b = {10, 20, 30, 40};
int x = 38;
vector<int> closest = findClosestPair(a, b, x);
cout << "[" << closest[0] << ", " << closest[1] << "]";
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
// Function to find the closest pair
void findClosestPair(int a[], int n, int b[], int m, int x) {
int l = 0, r = m - 1;
int diff = INT_MAX;
int res1 = 0, res2 = 0;
// Two pointer traversal
while (l < n && r >= 0) {
int sum = a[l] + b[r];
int currDiff = abs(sum - x);
// Update result if better pair found
if (currDiff < diff) {
diff = currDiff;
res1 = a[l];
res2 = b[r];
}
// Move pointers
if (sum > x)
r--;
else
l++;
}
printf("[%d, %d]", res1, res2);
}
int main() {
int a[] = {1, 4, 5, 7};
int b[] = {10, 20, 30, 40};
int x = 38;
int n = sizeof(a)/sizeof(a[0]);
int m = sizeof(b)/sizeof(b[0]);
findClosestPair(a, n, b, m, x);
return 0;
}
class GfG {
// Function to find the closest pair
static int[] findClosestPair(int[] a, int[] b, int x) {
int l = 0, r = b.length - 1;
int diff = Integer.MAX_VALUE;
int[] result = new int[2];
// Two pointer traversal
while (l < a.length && r >= 0) {
int sum = a[l] + b[r];
int currDiff = Math.abs(sum - x);
// Update result if better pair found
if (currDiff < diff) {
diff = currDiff;
result[0] = a[l];
result[1] = b[r];
}
// Move pointers
if (sum > x)
r--;
else
l++;
}
return result;
}
public static void main(String[] args) {
int[] a = {1, 4, 5, 7};
int[] b = {10, 20, 30, 40};
int x = 38;
int[] ans = findClosestPair(a, b, x);
System.out.println("[" + ans[0] + ", " + ans[1] + "]");
}
}
# Function to find the closest pair
def findClosestPair(a, b, x):
l, r = 0, len(b) - 1
diff = float('inf')
result = [0, 0]
# Two pointer traversal
while l < len(a) and r >= 0:
s = a[l] + b[r]
currDiff = abs(s - x)
# Update result if better pair found
if currDiff < diff:
diff = currDiff
result[0] = a[l]
result[1] = b[r]
# Move pointers
if s > x:
r -= 1
else:
l += 1
return result
a = [1, 4, 5, 7]
b = [10, 20, 30, 40]
x = 38
ans = findClosestPair(a, b, x)
print(ans)
using System;
class GfG {
// Function to find the closest pair
static int[] findClosestPair(int[] a, int[] b, int x) {
int l = 0, r = b.Length - 1;
int diff = int.MaxValue;
int[] result = new int[2];
// Two pointer traversal
while (l < a.Length && r >= 0) {
int sum = a[l] + b[r];
int currDiff = Math.Abs(sum - x);
// Update result if better pair found
if (currDiff < diff) {
diff = currDiff;
result[0] = a[l];
result[1] = b[r];
}
// Move pointers
if (sum > x)
r--;
else
l++;
}
return result;
}
static void Main() {
int[] a = {1, 4, 5, 7};
int[] b = {10, 20, 30, 40};
int x = 38;
int[] ans = findClosestPair(a, b, x);
Console.WriteLine("[" + ans[0] + ", " + ans[1] + "]");
}
}
// Function to find the closest pair
function findClosestPair(a, b, x) {
let l = 0, r = b.length - 1;
let diff = Number.MAX_VALUE;
let result = [0, 0];
// Two pointer traversal
while (l < a.length && r >= 0) {
let sum = a[l] + b[r];
let currDiff = Math.abs(sum - x);
// Update result if better pair found
if (currDiff < diff) {
diff = currDiff;
result[0] = a[l];
result[1] = b[r];
}
// Move pointers
if (sum > x)
r--;
else
l++;
}
return result;
}
let a = [1, 4, 5, 7];
let b = [10, 20, 30, 40];
let x = 38;
let ans = findClosestPair(a, b, x);
console.log(ans);
Output
[7, 30]