C Program to Find the closest pair from two sorted arrays
Last Updated :
20 Oct, 2023
Write a C program for a given two arrays arr1[0...m-1] and arr2[0..n-1], and a number x, the task is to find the pair arr1[i] + arr2[j] such that absolute value of (arr1[i] + arr2[j] - x) is minimum.
Example:
Input: ar1[] = {1, 4, 5, 7};
ar2[] = {10, 20, 30, 40};
x = 32
Output: 1 and 30
Input: ar1[] = {1, 4, 5, 7};
ar2[] = {10, 20, 30, 40};
x = 50
Output: 7 and 40
C Program to Find the closest pair from two sorted arrays using Nested Loop:
A Simple Solution is to run two loops. The outer loop considers every element of first array and inner loop checks for the pair in second array. We keep track of minimum difference between ar1[i] + ar2[j] and x.
Find the closest pair from two sorted arrays using Two pointer Technique:
Below is the idea to solve this problem in O(n) time using following steps. 1) Merge given two arrays into an auxiliary array of size m+n using merge process of merge sort. While merging keep another boolean array of size m+n to indicate whether the current element in merged array is from ar1[] or ar2[].
2) Consider the merged array and use the linear time algorithm to find the pair with sum closest to x. One extra thing we need to consider only those pairs which have one element from ar1[] and other from ar2[], we use the boolean array for this purpose.
Can we do it in a single pass and O(1) extra space?
The idea is to start from left side of one array and right side of another array, and use the algorithm same as step 2 of above approach.
Step-by-step approach:
- Initialize a variable diff as infinite (Diff is used to store the difference between pair and x). We need to find the minimum diff.
- Initialize two index variables l and r in the given sorted array.
(a) Initialize first to the leftmost index in ar1: l = 0
(b) Initialize second the rightmost index in ar2: r = n-1 - Loop while l< length.ar1 and r>=0
(a) If abs(ar1[l] + ar2[r] - sum) < diff then update diff and result
(b) If (ar1[l] + ar2[r] < sum ) then l++
(c) Else r-- - Print the result.
Below is the implementation of the above approach:
C
// C code for the above approach
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
// ar1[0..m-1] and ar2[0..n-1] are two given sorted arrays
// and x is the given number. This function prints the pair
// from both arrays such that the sum of the pair is closest
// to x.
void printClosest(int ar1[], int ar2[], int m, int n, int x)
{
// Initialize the difference between the pair sum and x.
int diff = INT_MAX;
// res_l and res_r are the result indexes from ar1[] and
// ar2[] respectively.
int res_l, res_r;
// Start from the left side of ar1[] and the right side
// of ar2[].
int l = 0, r = n - 1;
while (l < m && r >= 0) {
// If this pair is closer to x than the previously
// found closest, update res_l, res_r, and diff.
if (abs(ar1[l] + ar2[r] - x) < diff) {
res_l = l;
res_r = r;
diff = abs(ar1[l] + ar2[r] - x);
}
// If the sum of this pair is more than x, move to
// the smaller side.
if (ar1[l] + ar2[r] > x)
r--;
// Move to the greater side.
else
l++;
}
// Print the result.
printf("The closest pair is [%d, %d]\n", ar1[res_l],
ar2[res_r]);
}
// Drivers Code
int main()
{
int ar1[] = { 1, 4, 5, 7 };
int ar2[] = { 10, 20, 30, 40 };
int m = sizeof(ar1) / sizeof(ar1[0]);
int n = sizeof(ar2) / sizeof(ar2[0]);
int x = 38;
// Function call
printClosest(ar1, ar2, m, n, x);
return 0;
}
OutputThe closest pair is [7, 30]
Time Complexity : O(n)
Auxiliary Space : O(1)
C Program to Find the closest pair from two sorted arrays using Binary Search:
Since the two input arrays ar1 and ar2 are sorted, the comparison of the sum of the current pair with x essentially performs a binary search on the input array. By moving the left or right index based on the comparison result, the function implicitly divides the input array into two halves at each iteration, and therefore performs a binary search on the input array to find the closest pair.
Below is the implementation of the above approach:
C
// C code for the above approach
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
// Function to perform binary search on array ar2[] for
// the closest element to x
int binarySearch(int ar2[], int left, int right, int x)
{
if (left > right)
return left - 1;
int mid = (left + right) / 2;
if (ar2[mid] == x)
return mid;
else if (ar2[mid] > x)
return binarySearch(ar2, left, mid - 1, x);
else
return binarySearch(ar2, mid + 1, right, x);
}
// ar1[0..m-1] and ar2[0..n-1] are two given sorted arrays
// and x is a given number. This function prints the pair
// from both arrays such that the sum of the pair is closest
// to x.
void printClosest(int ar1[], int ar2[], int m, int n, int x)
{
// Initialize the diff between the pair sum and x.
int diff = INT_MAX;
// res_l and res_r are result indexes from ar1[] and
// ar2[] respectively.
int res_l, res_r;
// Start from the left side of ar1[] and the right side
// of ar2[].
int l = 0, r = n - 1;
while (l < m && r >= 0) {
// If this pair is closer to x than the previously
// found closest, then update res_l, res_r, and
// diff.
if (abs(ar1[l] + ar2[r] - x) < diff) {
res_l = l;
res_r = r;
diff = abs(ar1[l] + ar2[r] - x);
}
// If the sum of this pair is more than x, move to
// the smaller side.
if (ar1[l] + ar2[r] > x)
r--;
// Move to the greater side.
else
l++;
}
// Print the result.
printf("The closest pair is [%d, %d]\n", ar1[res_l],
ar2[res_r]);
}
// Drivers Code
int main()
{
int ar1[] = { 1, 4, 5, 7 };
int ar2[] = { 10, 20, 30, 40 };
int m = sizeof(ar1) / sizeof(ar1[0]);
int n = sizeof(ar2) / sizeof(ar2[0]);
int x = 38;
// Perform binary search on ar2[] for the element
// closest to x-ar1[i].
for (int i = 0; i < m; i++) {
int index = binarySearch(ar2, 0, n - 1, x - ar1[i]);
// Check if the element closest to x-ar1[i] is
// better than the current best.
if (index >= 0 && index < n
&& abs(ar1[i] + ar2[index] - x)
< abs(ar1[i] + ar2[index - 1] - x)) {
printClosest(ar1, ar2, m, n, x);
return 0;
}
else if (index > 0
&& abs(ar1[i] + ar2[index - 1] - x)
< abs(ar1[i] + ar2[index] - x)) {
index--;
}
}
return 0;
}
OutputThe closest pair is [7, 30]
Time Complexity: O(mLogN), As we are Dividing Arrays using Binary search where.
Auxiliary Space: O(1)
Please refer complete article on Find the closest pair from two sorted arrays for more details!
Similar Reads
Closest Pair of Points in C The Closest Pair of Points problem is a classic problem in computational geometry. It involves finding the pair of points with the smallest distance between them in a given set of points on a plane. This problem has significant applications, such as in air-traffic control where it is important to mo
6 min read
C Program to Find a pair with the given difference Given an unsorted array and a number n, find if there exists a pair of elements in the array whose difference is n. Examples: Input: arr[] = {5, 20, 3, 2, 50, 80}, n = 78 Output: Pair Found: (2, 80) Input: arr[] = {90, 70, 20, 80, 50}, n = 45 Output: No Such Pair Recommended: Please solve it on "PRA
3 min read
C Program to Find Common Array Elements Here, we will see how to find the common array elements using a C program. Input: a[6] = {1,2,3,4,5,6} b[6] = {5,6,7,8,9,10} Output: common array elements is 5 6 C // C program to find the common array elements #include <stdio.h> int main() { int a[6] = { 1, 2, 3, 4, 5, 6 }; int b[6] = { 5, 6,
1 min read
C Program to Find Common Array Elements Between Two Arrays Here we will build a C Program to Find Common Array Elements between Two Arrays. Given two arrays we have to find common elements in them using the below 2 approaches: Using Brute forceUsing Merge Sort and then Traversing Input: array1[] = {8, 2, 3, 4, 5, 6, 7, 1} array2[] = {4, 5, 7, 11, 6, 1} Outp
4 min read
C Program for Two Pointers Technique Two pointers is really an easy and effective technique which is typically used for searching pairs in a sorted array.Given a sorted array A (sorted in ascending order), having N integers, find if there exists any pair of elements (A[i], A[j]) such that their sum is equal to X. Letâs see the naive so
3 min read