Open In App

Find the closest pair from two sorted arrays

Last Updated : 20 Oct, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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: arr1[] = {1, 4, 5, 7};
arr2[] = {10, 20, 30, 40};
x = 32
Output: 1 and 30
Input: arr1[] = {1, 4, 5, 7};
arr2[] = {10, 20, 30, 40};
x = 50
Output: 7 and 40

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++ program to find the pair from two sorted arrays such
// that the sum of pair is closest to a given number x
#include <iostream>
#include <climits>
#include <cstdlib>
using namespace std;
 
// ar1[0..m-1] and ar2[0..n-1] are two given sorted arrays
// and x is 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 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 left side of ar1[] and 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 sum of this pair is more than x, move to smaller
       // side
       if (ar1[l] + ar2[r] > x)
           r--;
       else  // move to the greater side
           l++;
    }
 
    // Print the result
    cout << "The closest pair is [" << ar1[res_l] << ", "
         << ar2[res_r] << "] \n";
}
 
// Driver program to test above functions
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;
    printClosest(ar1, ar2, m, n, x);
    return 0;
}


Java




// Java program to find closest pair in an array
class ClosestPair
{
    // ar1[0..m-1] and ar2[0..n-1] are two given sorted
    // arrays/ and x is 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 pair sum and x.
        int diff = Integer.MAX_VALUE;
 
        // res_l and res_r are result indexes from ar1[] and ar2[]
        // respectively
        int res_l = 0, res_r = 0;
 
        // Start from left side of ar1[] and 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 (Math.abs(ar1[l] + ar2[r] - x) < diff)
           {
               res_l = l;
               res_r = r;
               diff = Math.abs(ar1[l] + ar2[r] - x);
           }
 
           // If sum of this pair is more than x, move to smaller
           // side
           if (ar1[l] + ar2[r] > x)
               r--;
           else  // move to the greater side
               l++;
        }
 
        // Print the result
        System.out.print("The closest pair is [" + ar1[res_l] +
                         ", " + ar2[res_r] + "]");
    }
 
    // Driver program to test above functions
    public static void main(String args[])
    {
        ClosestPair ob = new ClosestPair();
        int ar1[] = {1, 4, 5, 7};
        int ar2[] = {10, 20, 30, 40};
        int m = ar1.length;
        int n = ar2.length;
        int x = 38;
        ob.printClosest(ar1, ar2, m, n, x);
    }
}
/*This code is contributed by Rajat Mishra */


Python3




# Python3 program to find the pair from
# two sorted arrays such that the sum
# of pair is closest to a given number x
import sys
 
# ar1[0..m-1] and ar2[0..n-1] are two
# given sorted arrays and x is given
# number. This function prints the pair
# from both arrays such that the sum
# of the pair is closest to x.
def printClosest(ar1, ar2, m, n, x):
 
    # Initialize the diff between
    # pair sum and x.
    diff=sys.maxsize
 
    # res_l and res_r are result
    # indexes from ar1[] and ar2[]
    # respectively. Start from left
    # side of ar1[] and right side of ar2[]
    l = 0
    r = n-1
    while(l < m and 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 sum of this pair is more than x,
    # move to smaller side
        if ar1[l] + ar2[r] > x:
            r=r-1
        else: # move to the greater side
            l=l+1
     
 
    # Print the result
    print("The closest pair is [",
         ar1[res_l],",",ar2[res_r],"]")
 
# Driver program to test above functions
ar1 = [1, 4, 5, 7]
ar2 = [10, 20, 30, 40]
m = len(ar1)
n = len(ar2)
x = 38
printClosest(ar1, ar2, m, n, x)
 
# This code is contributed by Smitha Dinesh Semwal


C#




// C# program to find closest pair in
// an array
using System;
 
class GFG {
     
    // ar1[0..m-1] and ar2[0..n-1] are two
    // given sorted arrays/ and x is given
    // number. This function prints the
    // pair from both arrays such that the
    // sum of the pair is closest to x.
    static void printClosest(int []ar1,
            int []ar2, int m, int n, int x)
    {
         
        // Initialize the diff between pair
        // sum and x.
        int diff = int.MaxValue;
 
        // res_l and res_r are result
        // indexes from ar1[] and ar2[]
        // respectively
        int res_l = 0, res_r = 0;
 
        // Start from left side of ar1[]
        // and 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 (Math.Abs(ar1[l] +
                       ar2[r] - x) < diff)
            {
                res_l = l;
                res_r = r;
                diff = Math.Abs(ar1[l]
                            + ar2[r] - x);
            }
     
            // If sum of this pair is more
            // than x, move to smaller
            // side
            if (ar1[l] + ar2[r] > x)
                r--;
            else // move to the greater side
                l++;
        }
 
        // Print the result
        Console.Write("The closest pair is ["
                          + ar1[res_l] + ", "
                         + ar2[res_r] + "]");
    }
 
    // Driver program to test above functions
    public static void Main()
    {
        int []ar1 = {1, 4, 5, 7};
        int []ar2 = {10, 20, 30, 40};
        int m = ar1.Length;
        int n = ar2.Length;
        int x = 38;
         
        printClosest(ar1, ar2, m, n, x);
    }
}
 
// This code is contributed by nitin mittal.


Javascript




<script>
 
// Javascript program to find
// the pair from two sorted arrays such
// that the sum of pair is closest
// to a given number x
 
 
// ar1[0..m-1] and ar2[0..n-1] are
// two given sorted arrays
// and x is given number.
// This function prints the pair
// from both arrays such that the
// sum of the pair is closest to x.
function printClosest( ar1, ar2,  m, n, x)
{
    // Initialize the diff
    // between pair sum and x.
    let diff = Number.MAX_VALUE;
 
    // res_l and res_r are result
    // indexes from ar1[] and ar2[]
    // respectively
    let res_l, res_r;
 
    // Start from left side of ar1[] and
    // right side of ar2[]
    let 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 (Math.abs(ar1[l] + ar2[r] - x) < diff)
       {
           res_l = l;
           res_r = r;
           diff = Math.abs(ar1[l] + ar2[r] - x);
       }
 
       // If sum of this pair is more than x,
       // move to smaller side
       if (ar1[l] + ar2[r] > x)
           r--;
       else  // move to the greater side
           l++;
    }
 
    // Print the result
    document.write("The closest pair is [" + ar1[res_l] + ", "
         + ar2[res_r] + "] </br>");
}
 
 
    // driver code
     
    let ar1 = [1, 4, 5, 7];
    let ar2 = [10, 20, 30, 40];
    let m = ar1.length;
    let n = ar2.length;
    let x = 38;
    printClosest(ar1, ar2, m, n, x);
     
</script>


PHP




<?php
// PHP program to find the pair
// from two sorted arrays such
// that the sum of pair is
// closest to a given number x
 
// ar1[0..m-1] and ar2[0..n-1]
// are two given sorted arrays
// and x is given number. This
// function prints the pair from
// both arrays such that the sum
// of the pair is closest to x.
function printClosest($ar1, $ar2,
                      $m, $n, $x)
{
     
    // Initialize the diff between
    // pair sum and x.
    $diff = PHP_INT_MAX;
 
    // res_l and res_r are result
    // indexes from ar1[] and ar2[]
    // respectively
    $res_l;
    $res_r;
 
    // Start from left side of
    // ar1[] and right side of ar2[]
    $l = 0;
    $r = $n - 1;
    while ($l < $m and $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 sum of this pair is
        // more than x, move to smaller
        // side
        if ($ar1[$l] + $ar2[$r] > $x)
            $r--;
             
        // move to the greater side
        else
            $l++;
    }
 
    // Print the result
    echo "The closest pair is [" , $ar1[$res_l] , ", "
                               , $ar2[$res_r] , "] \n";
}
 
    // Driver Code
    $ar1 = array(1, 4, 5, 7);
    $ar2 = array(10, 20, 30, 40);
    $m = count($ar1);
    $n = count($ar2);
    $x = 38;
    printClosest($ar1, $ar2, $m, $n, $x);
 
// This code is contributed by anuj_67.
?>


Output: 

 The closest pair is [7, 30] 

Time Complexity : O(n) 
Auxiliary Space : O(1)

Find the closest pair from two sorted arrays using Binary Search:

Since the two input arrays arr1 and arr2 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++




#include <iostream>
#include <climits>
#include <cstdlib>
using namespace std;
 
// 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 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 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 left side of ar1[] and 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 sum of this pair is more than x, move to smaller
        // side
        if (ar1[l] + ar2[r] > x)
            r--;
        else // move to the greater side
            l++;
    }
 
    // Print the result
    cout << "The closest pair is [" << ar1[res_l] << ", "
         << ar2[res_r] << "] \n";
}
 
// Driver program to test above functions
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--;
        }
    }
}
 
       


Java




import java.util.*;
 
public class ClosestSumPair {
     
    // Function to perform binary search on array ar2[] for
    // the closest element to x
    public static 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 given number. This function prints the pair from
    // both arrays such that the sum of the pair is closest to x.
    public static void printClosest(int ar1[], int ar2[], int m, int n, int x) {
        // Initialize the diff between pair sum and x.
        int diff = Integer.MAX_VALUE;
     
        // res_l and res_r are result indexes from ar1[] and ar2[]
        // respectively
        int res_l = 0, res_r = 0;
     
        // Start from left side of ar1[] and 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 (Math.abs(ar1[l] + ar2[r] - x) < diff) {
                res_l = l;
                res_r = r;
                diff = Math.abs(ar1[l] + ar2[r] - x);
            }
     
            // If sum of this pair is more than x, move to smaller
            // side
            if (ar1[l] + ar2[r] > x)
                r--;
            else // move to the greater side
                l++;
        }
     
        // Print the result
        System.out.println("The closest pair is [" + ar1[res_l] + ", " + ar2[res_r] + "]");
    }
     
    // Driver program to test above functions
    public static void main(String args[]) {
        int ar1[] = {1, 4, 5, 7};
        int ar2[] = {10, 20, 30, 40};
        int m = ar1.length;
        int n = ar2.length;
        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 && Math.abs(ar1[i]+ar2[index]-x) < Math.abs(ar1[i]+ar2[index-1]-x)) {
                printClosest(ar1, ar2, m, n, x);
                return;
            } else if (index > 0 && Math.abs(ar1[i]+ar2[index-1]-x) < Math.abs(ar1[i]+ar2[index]-x)) {
                index--;
            }
        }
    }
}
           


Python3




import sys
 
# Function to perform binary search on array ar2[] for
# the closest element to x
def binarySearch(ar2, left, right, x):
    if left > right:
        return left-1
    mid = (left + right) // 2
    if ar2[mid] == x:
        return mid
    elif 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 given number. This function prints the pair from
# both arrays such that the sum of the pair is closest to x.
def printClosest(ar1, ar2, m, n, x):
    # Initialize the diff between pair sum and x.
    diff = sys.maxsize
 
    # res_l and res_r are result indexes from ar1[] and ar2[]
    # respectively
    res_l, res_r = 0, 0
 
    # Start from left side of ar1[] and right side of ar2[]
    l, r = 0, n - 1
    while l < m and 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 sum of this pair is more than x, move to smaller
        # side
        if ar1[l] + ar2[r] > x:
            r -= 1
        else: # move to the greater side
            l += 1
 
    # Print the result
    print("The closest pair is [{}, {}]".format(ar1[res_l], ar2[res_r]))
 
# Driver program to test above functions
if __name__ == "__main__":
    ar1 = [1, 4, 5, 7]
    ar2 = [10, 20, 30, 40]
    m = len(ar1)
    n = len(ar2)
    x = 38
 
    # Perform binary search on ar2[] for the element closest
    # to x-ar1[i]
    for i in range(m):
        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 and index < n and abs(ar1[i]+ar2[index]-x) < abs(ar1[i]+ar2[index-1]-x):
            printClosest(ar1, ar2, m, n, x)
            break
        elif index > 0 and abs(ar1[i]+ar2[index-1]-x) < abs(ar1[i]+ar2[index]-x):
            index -= 1


C#




using System;
 
public class MainClass
{
 
  // Function to perform binary search on array ar2[] for
  // the closest element to x
  public static 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 given number. This function prints
  // the pair from both arrays such that the sum of the
  // pair is closest to x.
  public static void PrintClosest(int[] ar1, int[] ar2,
                                  int m, int n, int x)
  {
    // Initialize the diff between pair sum and x.
    int diff = int.MaxValue;
 
    // res_l and res_r are result indexes from ar1[] and
    // ar2[] respectively
    int res_l = 0, res_r = 0;
 
    // Start from left side of ar1[] and 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 (Math.Abs(ar1[l] + ar2[r] - x) < diff) {
        res_l = l;
        res_r = r;
        diff = Math.Abs(ar1[l] + ar2[r] - x);
      }
 
      // If sum of this pair is more than x, move to
      // smaller side
      if (ar1[l] + ar2[r] > x)
        r--;
      else // move to the greater side
        l++;
    }
 
    // Print the result
    Console.WriteLine("The closest pair is ["
                      + ar1[res_l] + ", " + ar2[res_r]
                      + "]");
  }
 
  // Driver program to test above functions
  public static void Main()
  {
    int[] ar1 = { 1, 4, 5, 7 };
    int[] ar2 = { 10, 20, 30, 40 };
    int m = ar1.Length;
    int n = ar2.Length;
    int x = 38;
 
    // Sort the second array
    Array.Sort(ar2);
 
    // 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
          && Math.Abs(ar1[i] + ar2[index] - x)
          < Math.Abs(ar1[i] + ar2[index - 1]
                     - x)) {
        PrintClosest(ar1, ar2, m, n, x);
        return;
      }
      else if (index > 0
               && Math.Abs(ar1[i] + ar2[index - 1]
                           - x)
               < Math.Abs(ar1[i] + ar2[index]
                          - x)) {
        PrintClosest(ar1, ar2, m, n, x);
        return;
      }
    }
  }
}


Javascript




// Function to perform binary search on array arr for
// the closest element to x
function binarySearch(arr, left, right, x) {
if (left > right) {
return left - 1;
}
const mid = Math.floor((left + right) / 2);
if (arr[mid] === x) {
return mid;
} else if (arr[mid] > x) {
return binarySearch(arr, left, mid - 1, x);
} else {
return binarySearch(arr, mid + 1, right, x);
}
}
// arr1 and arr2 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.
function printClosest(arr1, arr2, x) {
const m = arr1.length;
const n = arr2.length;
// Initialize the diff between pair sum and x.
let diff = Infinity;
 
// res_l and res_r are result indexes from arr1 and arr2
// respectively
let res_l = 0,
res_r = 0;
 
// Start from left side of arr1 and right side of arr2
let 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 (Math.abs(arr1[l] + arr2[r] - x) < diff) {
res_l = l;
res_r = r;
diff = Math.abs(arr1[l] + arr2[r] - x);
}
// If sum of this pair is more than x, move to smaller
// side
if (arr1[l] + arr2[r] > x) {
  r -= 1;
} else {
  // move to the greater side
  l += 1;
}
 
// Print the result
console.log(The closest pair is [${arr1[res_l]}, ${arr2[res_r]}]);
}
 
// Driver program to test above functions
const arr1 = [1, 4, 5, 7];
const arr2 = [10, 20, 30, 40];
const x = 38;
 
// Perform binary search on arr2 for the element closest
// to x-arr1[i]
for (let i = 0; i < arr1.length; i++) {
const index = binarySearch(arr2, 0, arr2.length - 1, x - arr1[i]);
 
// Check if the element closest to x-arr1[i] is better
// than the current best
if (
index >= 0 &&
index < arr2.length &&
Math.abs(arr1[i] + arr2[index] - x) <
Math.abs(arr1[i] + arr2[index - 1] - x)
) {
printClosest(arr1, arr2, x);
break;
} else if (
index > 0 &&
Math.abs(arr1[i] + arr2[index - 1] - x) <
Math.abs(arr1[i] + arr2[index] - x)
) {
index -= 1;
}
}


OUTPUT:

The closest pair is [7, 30] 

Time Complexity : O(mLogN) , As we are Dividing Arrays using Binary search where.
Auxiliary Space : O(1)
 

Smallest Difference pair of values between two unsorted Arrays

 



Previous Article
Next Article

Similar Reads

Check if two sorted arrays can be merged to form a sorted array with no adjacent pair from the same array
Given two sorted arrays A[] and B[] of size N, the task is to check if it is possible to merge two given sorted arrays into a new sorted array such that no two consecutive elements are from the same array. Examples: Input: A[] = {3, 5, 8}, B[] = {2, 4, 6}Output: Yes Explanation: Merged array = {B[0], A[0], B[1], A[1], B[2], A[2]} Since the resultan
15+ min read
Generate all possible sorted arrays from alternate elements of two given sorted arrays
Given two sorted arrays A and B, generate all possible arrays such that the first element is taken from A then from B then from A, and so on in increasing order till the arrays are exhausted. The generated arrays should end with an element from B. Example: A = {10, 15, 25} B = {1, 5, 20, 30} The resulting arrays are: 10 20 10 20 25 30 10 30 15 20 1
12 min read
Given a sorted array and a number x, find the pair in array whose sum is closest to x
Given a sorted array and a number x, find a pair in an array whose sum is closest to x. Examples: Input: arr[] = {10, 22, 28, 29, 30, 40}, x = 54 Output: 22 and 30 Input: arr[] = {1, 3, 4, 7, 10}, x = 15 Output: 4 and 10Naive Approach:- A simple solution is to consider every pair and keep track of the closest pair (the absolute difference between p
15+ min read
Find three closest elements from given three sorted arrays
Given three sorted arrays A[], B[] and C[], find 3 elements i, j and k from A, B and C respectively such that max(abs(A[i] - B[j]), abs(B[j] - C[k]), abs(C[k] - A[i])) is minimized. Here abs() indicates absolute value. Example : Input : A[] = {1, 4, 10} B[] = {2, 15, 20} C[] = {10, 12} Output: 10 15 10Explanation: 10 from A, 15 from B and 10 from C
15+ min read
Find the pairs of IDs from two arrays having sum less than target closest to it
Given two arrays arr1[] and arr2[] of pairs of the form {ID, value} of size N and M respectively and an integer target, the task is to find all the pairs of IDs from both the arrays such that the sum of the values of the pairs is maximum and has a value at most M. Examples: Input: arr1[] = [[1, 2000], [2, 3000], [3, 2000]], arr2[] = [[1, 2500], [2,
9 min read
Find triplet sum closest to X in a sorted Doubly Linked List (DLL)
Given a sorted doubly linked list of N nodes and an integer X, the task is to find the sum of three nodes in the list which is closest to X. Examples: Input: DLL: -8 ? 2 ? 3 ? 4 ? 5, X = 1Output: 1Explanation: The required three integers {-8, 4, 5} whose sum is 1 and is closest to 1. Input: DLL: 1 ? 2 ? 3 ? 4, X = 3 Output: 6Explanation: The requir
11 min read
Find closest number in Sorted array
Given an array of sorted integers. We need to find the closest value to the given number. Array may contain duplicate values and negative numbers. Examples: Input : arr[] = {1, 2, 4, 5, 6, 6, 8, 9} Target number = 11Output : 99 is closest to 11 in given arrayInput :arr[] = {2, 5, 6, 7, 8, 8, 9}; Target number = 4Output : 55 is closest to 4 in given
15+ min read
Closest Pair of Points using Divide and Conquer algorithm
We are given an array of n points in the plane, and the problem is to find out the closest pair of points in the array. This problem arises in a number of applications. For example, in air-traffic control, you may want to monitor planes that come too close together, since this may indicate a possible collision. Recall the following formula for dist
15+ min read
Closest pair in an Array such that one number is multiple of the other
Given an array arr[] of integers of size N, the task is to find the closest pair in the given array such that one element is the multiple of the other. If no such pair exists then print -1. Note: Closest pair means the difference between the index of any two elements must be minimum. Examples: Input: arr[] = {2, 3, 4, 5, 6}Output: 2 4Explanation: T
6 min read
Distance between closest pair of islands
Given a grid[][] containing 0s and 1s, where '0' represents water and '1' represents the land. Given that an island is a group of land (1s) surrounded by water (0s) on all sides. The task is to find the distance between the two closest islands such that: Distance between two islands is the minimum number of '0' between two islands.Only 4 - directio
15+ min read
three90RightbarBannerImg