Open In App

Given a sorted array and a number x, find the pair in array whose sum is closest to x

Last Updated : 19 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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 10

Naive Approach:- A simple solution is to consider every pair and keep track of the closest pair (the absolute difference between pair sum and x is minimum). Finally, print the closest pair. The time complexity of this solution is O(n2)

Implementation:- 

C++




// Simple C++ program to find the pair with sum closest to a given no.
#include <bits/stdc++.h>
using namespace std;
  
// Prints the pair with sum closest to x
void printClosest(int arr[], int n, int x)
{
    int res_l, res_r;  // To store indexes of result pair
    
      //variable to store current minimum difference
      int temp = INT_MAX;
    
      //iterating over array
      for(int i=0;i<n-1;i++)
    {
          for(int j=i+1;j<n;j++)
        {
              //if found more closest pair
              if(abs(arr[i]+arr[j]-x)<temp)
            {
                  res_l=i;
                  res_r=j;
                  temp=abs(arr[i]+arr[j]-x);
            }
        }
    }
  
    cout <<" The closest pair is " << arr[res_l] << " and " << arr[res_r];
}
  
// Driver program to test above functions
int main()
{
    int arr[] =  {10, 22, 28, 29, 30, 40}, x = 54;
    int n = sizeof(arr)/sizeof(arr[0]);
    printClosest(arr, n, x);
    return 0;
}
// Code By shubhamrajput6156


Java




// Simple Java program to find the pair 
// with sum closest to a given no.
import java.util.*;
  
class GFG {
  
  // Function to Prints the pair with sum closest to x
  public static void printClosest(int[] arr, int n, int x)
  {
    int res_l = 0,
    res_r = 0; // To store indexes of result pair
  
    // variable to store current minimum difference
    int temp = Integer.MAX_VALUE;
  
    // iterating over array
    for (int i = 0; i < n - 1; i++) {
      for (int j = i + 1; j < n; j++) {
        // if found more closest pair
        if (Math.abs(arr[i] + arr[j] - x) < temp) {
          res_l = i;
          res_r = j;
          temp = Math.abs(arr[i] + arr[j] - x);
        }
      }
    }
  
    System.out.println("The closest pair is "
                       + arr[res_l] + " and "
                       + arr[res_r]);
  }
  
  // Driver program to test above functions
  public static void main(String[] args)
  {
    int[] arr = { 10, 22, 28, 29, 30, 40 };
    int x = 54;
    int n = arr.length;
    printClosest(arr, n, x);
  }
}
  
// This code is Contributed by Prasad Kandekar(prasad264)


Python3




# Python3 program to find the pair
# with sum
# closest to a given no.
  
import sys
  
# Prints the pair with sum closest to x
  
def printClosest(arr, n, x):
    res_l = res_r = 0    # To store indexes of result pair
    temp = sys.maxsize    # variable to store current minimum difference    
  
    for i in range(n-1):
        for j in range(i+1, n):
              # if found more closest pair
            if abs(arr[i] + arr[j] - x) < temp:
                res_l = i
                res_r = j
                temp = abs(arr[i] + arr[j] - x)
      
    print("The closest pair is", arr[res_l], "and", arr[res_r])
  
#driver code
arr = [10, 22, 28, 29, 30, 40]
x = 54
n = len(arr)
printClosest(arr, n, x)


C#




// Simple C# program to find the pair with sum closest to a given no.
using System;
public class GFG {
  
  // Prints the pair with sum closest to x
  static void PrintClosest(int[] arr, int n, int x)
  {
    // To store indexes of result pair
    int res_l = 0, res_r = 0; 
  
    // variable to store current minimum difference
    int temp = int.MaxValue;
  
    // iterating over array
    for (int i = 0; i < n - 1; i++) {
      for (int j = i + 1; j < n; j++) {
  
        // if found more closest pair
        if (Math.Abs(arr[i] + arr[j] - x) < temp) {
          res_l = i;
          res_r = j;
          temp = Math.Abs(arr[i] + arr[j] - x);
        }
      }
    }
  
    Console.WriteLine("The closest pair is "
                      + arr[res_l] + " and "
                      + arr[res_r]);
  }
  
  // Driver program to test above functions
  static public void Main(string[] args)
  {
    int[] arr = { 10, 22, 28, 29, 30, 40 };
    int x = 54;
    int n = arr.Length;
    PrintClosest(arr, n, x);
  }
}
  
// This Code is Contributed by Prasad Kandekar(prasad264)


Javascript




// Simple JavaScript program to find the pair with sum closest to a given number.
  
// Function to find the pair with sum closest to x
function printClosest(arr, n, x) {
    let res_l, res_r; // To store indexes of result pair
  
    // Variable to store current minimum difference
    let temp = Number.MAX_SAFE_INTEGER;
  
    // Iterating over array
    for (let i = 0; i < n - 1; i++) {
        for (let j = i + 1; j < n; j++) {
            // If found more closest pair
            if (Math.abs(arr[i] + arr[j] - x) < temp) {
                res_l = i;
                res_r = j;
                temp = Math.abs(arr[i] + arr[j] - x);
            }
        }
    }
  
    console.log("The closest pair is " + arr[res_l] + " and " + arr[res_r]);
}
  
// Driver program to test above function
let arr = [10, 22, 28, 29, 30, 40];
let x = 54;
let n = arr.length;
printClosest(arr, n, x);
  
// This code is contributed By Prajwal Kandekar


Output

 The closest pair is 22 and 30

Time Complexity:- O(N^2)
Auxiliary Space:- O(1)

Binary Search Approach:- The more efficient solution than the above approach is to use Binary Search because the given array is in a sorted format.

Step-by-step algorithm for implementing the above approach:

  • Initialize variables:
    • l and r to point to the first and last elements of the array, respectively.
    • res_l and res_r to store the indexes of the closest pair.
    • minDiff to store the current minimum difference.
  •  Iterate over the array using a loop:
    • Set e to the current element.
    • While left is less than or equal to right:
      • Set mid to the middle element of the subarray.
      •  If arr[mid] + e is equal to x
        • set res_l to i, res_r to mid, and minDiff to 0. Break out of the loop.
      •  If abs(arr[mid] + e – x) is less than minDiff,
        • set minDiff to abs(arr[mid] + e – x) and res_l to i 
      •  and res_r to mid.
      •  If arr[mid] + e is less than x, set left to mid + 1.
      •  Otherwise, set right to mid – 1.   
    • Set left and right to point to the first and last elements of the remaining subarray, respectively. 
  •   Print the pair with the values of arr[res_l] and arr[res_r].

C++




// C++ program to find the pair with sum closest 
// to a given no using above approach.
#include <bits/stdc++.h>
using namespace std;
  
// Function to prints the pair with sum closest to x
void closestPair(int arr[], int n, int x) {
        
      // Initialize variables pointing to the 
      // first and last elements of the array
    int l = 0, r = n - 1;
    
      // To store indexes of result pair
    int res_l, res_r;
    
      // variable to store current minimum difference
    int minDiff = INT_MAX;
  
      // Iterate over the array using
    for (int i = 0; i < n; i++) {
        int e = arr[i];
          
        // Use binary search to find the element 
        // 'elem' in the array such that 'e+elem'
        // is closest to 'x'.
        int left = i + 1, right = n - 1;
        while (left <= right) {
            int mid = (left + right) / 2;
  
            if (arr[mid] + e == x) {
                res_l = i;
                res_r = mid;
                minDiff = 0;
                break;
            }
              
            // Check if this pair is closer than the 
            // closest pair so far
            if (abs(arr[mid] + e - x) < minDiff) {
                minDiff = abs(arr[mid] + e - x);
                res_l = i;
                res_r = mid;
            }
  
            if (arr[mid] + e < x) {
                left = mid + 1;
            }
              
            else {
                right = mid - 1;
            }
        }
    }
    // Print the pair
    cout << "The closest pair is " << arr[res_l] << " and " << arr[res_r];
}
  
// Driver program to test above functions
int main() {
    int arr[] = {10, 22, 28, 29, 30, 40};
    int x = 54;
    int n = sizeof(arr) / sizeof(arr[0]);
  
      // Function Call
    closestPair(arr, n, x);
    return 0;
}
  
// This Code is Contributed by Prasad Kandekar(prasad264)


Java




import java.util.*;
  
public class Main {
    public static void main(String[] args)
    {
        // Initialize the array
        int[] arr = { 10, 22, 28, 29, 30, 40 };
        // Initialize the target sum
        int x = 54;
        // Get the length of the array
        int n = arr.length;
        // Call the closestPair function
        closestPair(arr, n, x);
    }
  
    // Function to find the pair with sum closest to a given
    // no using above approach
    public static void closestPair(int[] arr, int n, int x)
    {
        // Initialize variables pointing to the first and
        // last elements of the array
        int l = 0, r = n - 1;
        // To store indexes of result pair
        int res_l = 0, res_r = 0;
        // variable to store current minimum difference
        int minDiff = Integer.MAX_VALUE;
  
        // Iterate over the array
        for (int i = 0; i < n; i++) {
            int e = arr[i];
            // Use binary search to find the element 'elem'
            // in the array such that 'e+elem' is closest to
            // 'x'.
            int left = i + 1, right = n - 1;
            while (left <= right) {
                int mid = (left + right) / 2;
  
                if (arr[mid] + e == x) {
                    res_l = i;
                    res_r = mid;
                    minDiff = 0;
                    break;
                }
  
                // Check if this pair is closer than the
                // closest pair so far
                if (Math.abs(arr[mid] + e - x) < minDiff) {
                    minDiff = Math.abs(arr[mid] + e - x);
                    res_l = i;
                    res_r = mid;
                }
  
                if (arr[mid] + e < x) {
                    left = mid + 1;
                }
                else {
                    right = mid - 1;
                }
            }
        }
        // Print the pair
        System.out.println("The closest pair is "
                           + arr[res_l] + " and "
                           + arr[res_r]);
    }
}


Python3




# Python program to find the pair with sum closest
# to a given no using above approach.
import sys
  
# Function to prints the pair with sum closest to x
def closestPair(arr, n, x):
    
    # Initialize variables pointing to the
    # first and last elements of the array
    l, r = 0, n - 1
  
    # To store indexes of result pair
    res_l, res_r = 0, 0
  
    # variable to store current minimum difference
    minDiff = sys.maxsize
  
    # Iterate over the array using
    for i in range(n):
        e = arr[i]
  
        # Use binary search to find the element
        # 'elem' in the array such that 'e+elem'
        # is closest to 'x'.
        left, right = i + 1, n - 1
        while left <= right:
            mid = (left + right) // 2
  
            if arr[mid] + e == x:
                res_l = i
                res_r = mid
                minDiff = 0
                break
  
            # Check if this pair is closer than the
            # closest pair so far
            if abs(arr[mid] + e - x) < minDiff:
                minDiff = abs(arr[mid] + e - x)
                res_l = i
                res_r = mid
  
            if arr[mid] + e < x:
                left = mid + 1
            else:
                right = mid - 1
  
    # Print the pair
    print("The closest pair is", arr[res_l], "and", arr[res_r])
  
  
# Driver program to test above functions
arr = [10, 22, 28, 29, 30, 40]
x = 54
n = len(arr)
  
# Function Call
closestPair(arr, n, x)
  
# This Code is Contributed by prasad264


C#




using System;
  
class Program {
  // Function to prints the pair with sum closest to x
  static void closestPair(int[] arr, int n, int x) {
  
    // Initialize variables pointing to the 
    // first and last elements of the array
    int l = 0, r = n - 1;
  
    // To store indexes of result pair
    int res_l = -1, res_r = -1;
  
    // variable to store current minimum difference
    int minDiff = int.MaxValue;
  
    // Iterate over the array using
    for (int i = 0; i < n; i++) {
      int e = arr[i];
  
      // Use binary search to find the element 
      // 'elem' in the array such that 'e+elem'
      // is closest to 'x'.
      int left = i + 1, right = n - 1;
      while (left <= right) {
        int mid = (left + right) / 2;
  
        if (arr[mid] + e == x) {
          res_l = i;
          res_r = mid;
          minDiff = 0;
          break;
        }
  
        // Check if this pair is closer than the 
        // closest pair so far
        if (Math.Abs(arr[mid] + e - x) < minDiff) {
          minDiff = Math.Abs(arr[mid] + e - x);
          res_l = i;
          res_r = mid;
        }
  
        if (arr[mid] + e < x) {
          left = mid + 1;
        }
        else {
          right = mid - 1;
        }
      }
    }
  
    // Print the pair
    Console.WriteLine($"The closest pair is {arr[res_l]} and {arr[res_r]}");
  }
  
  // Driver program to test above functions
  static void Main(string[] args) {
    int[] arr = { 10, 22, 28, 29, 30, 40 };
    int x = 54;
    int n = arr.Length;
  
    // Function Call
    closestPair(arr, n, x);
  }
}


Javascript




// JavaScript program to find the pair with sum closest
// to a given no using above approach.
  
// Function to prints the pair with sum closest to x
function closestPair(arr, n, x) {
    // Initialize variables pointing to the
    // first and last elements of the array
    let l = 0, r = n - 1;
      
    // To store indexes of result pair
    let res_l, res_r;
      
    // variable to store current minimum difference
    let minDiff = Number.MAX_SAFE_INTEGER;
      
    // Iterate over the array using
    for (let i = 0; i < n; i++) {
        let e = arr[i];
      
        // Use binary search to find the element 
        // 'elem' in the array such that 'e+elem'
        // is closest to 'x'.
        let left = i + 1, right = n - 1;
        while (left <= right) {
            let mid = Math.floor((left + right) / 2);
      
            if (arr[mid] + e == x) {
                res_l = i;
                res_r = mid;
                minDiff = 0;
                break;
            }
      
            // Check if this pair is closer than the 
            // closest pair so far
            if (Math.abs(arr[mid] + e - x) < minDiff) {
                minDiff = Math.abs(arr[mid] + e - x);
                res_l = i;
                res_r = mid;
            }
      
            if (arr[mid] + e < x) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
    }
    // Print the pair
    console.log(`The closest pair is ${arr[res_l]} and ${arr[res_r]}`);
}
  
// Driver program to test above functions
let arr = [10, 22, 28, 29, 30, 40];
let x = 54;
let n = arr.length;
  
// Function Call
closestPair(arr, n, x);


Output

The closest pair is 22 and 30

Complexity Analysis:

Time Complexity: O(n log n), because we are using a binary search algorithm to search for the pair, and for each element, we are performing a binary search, which has a time complexity of O(logn). Hence, the total time complexity of the approach becomes O(n log n).
Auxiliary Space: O(1), because we are not using any extra space to store the elements of the array or the result. The only extra space used is for storing some variables, which is constant and does not depend on the size of the input.

Efficient Approach:- An efficient solution can find the pair in O(n) time. The idea is similar to method 1 of this post. The following is a detailed algorithm. 

1) Initialize a variable diff as infinite (Diff is used to store the 
   difference between pair and x).  We need to find the minimum diff.
2) Initialize two index variables l and r in the given sorted array.
       (a) Initialize first to the leftmost index:  l = 0
       (b) Initialize second  the rightmost index:  r = n-1
3) Loop while l < r.
       (a) If  abs(arr[l] + arr[r] - sum) < diff  then 
           update diff and result 
       (b) If(arr[l] + arr[r] <  sum )  then l++
       (c) Else r--    

Following is the implementation of the above algorithm.

C++14




// Simple C++ program to find the pair with sum closest to a given no.
#include <bits/stdc++.h>
using namespace std;
  
// Prints the pair with sum closest to x
void printClosest(int arr[], int n, int x)
{
    int res_l, res_r;  // To store indexes of result pair
  
    // Initialize left and right indexes and difference between
    // pair sum and x
    int l = 0, r = n-1, diff = INT_MAX;
  
    // While there are elements between l and r
    while (r > l)
    {
       // Check if this pair is closer than the closest pair so far
       if (abs(arr[l] + arr[r] - x) < diff)
       {
           res_l = l;
           res_r = r;
           diff = abs(arr[l] + arr[r] - x);
       }
  
       // If this pair has more sum, move to smaller values.
       if (arr[l] + arr[r] > x)
           r--;
       else // Move to larger values
           l++;
    }
  
    cout <<" The closest pair is " << arr[res_l] << " and " << arr[res_r];
}
  
// Driver program to test above functions
int main()
{
    int arr[] =  {10, 22, 28, 29, 30, 40}, x = 54;
    int n = sizeof(arr)/sizeof(arr[0]);
    printClosest(arr, n, x);
    return 0;
}
// Code By Mayur Patil


Java




// Java program to find pair with sum closest to x
import java.io.*;
import java.util.*;
import java.lang.Math;
  
class CloseSum {
      
    // Prints the pair with sum closest to x
    static void printClosest(int arr[], int n, int x)
    {
        int res_l=0, res_r=0// To store indexes of result pair
   
        // Initialize left and right indexes and difference between
        // pair sum and x
        int l = 0, r = n-1, diff = Integer.MAX_VALUE;
   
        // While there are elements between l and r
        while (r > l)
        {
            // Check if this pair is closer than the closest pair so far
            if (Math.abs(arr[l] + arr[r] - x) < diff)
            {
               res_l = l;
               res_r = r;
               diff = Math.abs(arr[l] + arr[r] - x);
            }
   
            // If this pair has more sum, move to smaller values.
            if (arr[l] + arr[r] > x)
               r--;
            else // Move to larger values
               l++;
        }
   
    System.out.println(" The closest pair is "+arr[res_l]+" and "+ arr[res_r]);
}
      
      
    // Driver program to test above function
    public static void main(String[] args)
    {
        int arr[] =  {10, 22, 28, 29, 30, 40}, x = 54;
        int n = arr.length;
        printClosest(arr, n, x);        
    }
}
/*This code is contributed by Devesh Agrawal*/


Python3




# Python3 program to find the pair
# with sum 
# closest to a given no.
  
# A sufficiently large value greater
# than any 
# element in the input array
MAX_VAL = 1000000000
  
  
#Prints the pair with sum closest to x
  
def printClosest(arr, n, x):
      
    # To store indexes of result pair
    res_l, res_r = 0, 0
      
    #Initialize left and right indexes
    # and difference between
    # pair sum and x
    l, r, diff = 0, n-1, MAX_VAL
      
    # While there are elements between l and r
    while r > l:
        # Check if this pair is closer than the 
        # closest pair so far
        if abs(arr[l] + arr[r] - x) < diff:
            res_l = l
            res_r = r
            diff = abs(arr[l] + arr[r] - x)
      
        if arr[l] + arr[r] > x:
        # If this pair has more sum, move to 
        # smaller values.
            r -= 1
        else:
        # Move to larger values
            l += 1
          
    print('The closest pair is {} and {}'
         .format(arr[res_l], arr[res_r]))
  
  
# Driver code to test above
if __name__ == "__main__":
    arr = [10, 22, 28, 29, 30, 40]
    n = len(arr)
    x=54
    printClosest(arr, n, x)
  
# This code is contributed by Tuhin Patra


C#




// C# program to find pair with sum closest to x
using System;
  
class GFG {
      
    // Prints the pair with sum closest to x
    static void printClosest(int []arr, int n, int x)
    {
          
        // To store indexes of result pair
        int res_l = 0, res_r = 0; 
  
        // Initialize left and right indexes and 
        // difference between pair sum and x
        int l = 0, r = n-1, diff = int.MaxValue;
  
        // While there are elements between l and r
        while (r > l)
        {
              
            // Check if this pair is closer than the
            // closest pair so far
            if (Math.Abs(arr[l] + arr[r] - x) < diff)
            {
                res_l = l;
                res_r = r;
                diff = Math.Abs(arr[l] + arr[r] - x);
            }
  
            // If this pair has more sum, move to
            // smaller values.
            if (arr[l] + arr[r] > x)
            r--;
            else // Move to larger values
            l++;
        }
      
        Console.Write(" The closest pair is " +
                 arr[res_l] + " and " + arr[res_r]);
    }
      
    // Driver program to test above function
    public static void Main()
    {
        int []arr = {10, 22, 28, 29, 30, 40};
        int x = 54;
        int n = arr.Length;
          
        printClosest(arr, n, x);     
    }
}
  
// This code is contributed by nitin mittal.


PHP




<?php
// Simple PHP program to find the
// pair with sum closest to a 
// given no.
  
// Prints the pair with
// sum closest to x
function printClosest($arr, $n, $x)
{
      
    // To store indexes
    // of result pair
    $res_l;
    $res_r
  
    // Initialize left and right 
    // indexes and difference between
    // pair sum and x
    $l = 0; 
    $r = $n - 1;
    $diff = PHP_INT_MAX;
  
    // While there are elements
    // between l and r
    while ($r > $l)
    {
          
        // Check if this pair is closer 
        // than the closest pair so far
        if (abs($arr[$l] + $arr[$r] - $x) < 
                                      $diff)
        {
            $res_l = $l;
            $res_r = $r;
            $diff = abs($arr[$l] + $arr[$r] - $x);
        }
      
        // If this pair has more sum, 
        // move to smaller values.
        if ($arr[$l] + $arr[$r] > $x)
            $r--;
              
        // Move to larger values
        else 
            $l++;
    }
  
    echo " The closest pair is " 
         , $arr[$res_l] ," and " 
         , $arr[$res_r];
}
  
    // Driver Code
    $arr = array(10, 22, 28, 29, 30, 40); 
    $x = 54;
    $n = count($arr);
    printClosest($arr, $n, $x);
      
// This code is contributed by anuj_67.
?>


Javascript




<script>
  
// JavaScript program to find pair
// with sum closest to x
  
      
    // Prints the pair with sum closest to x
    function printClosest(arr,n,x)
    {
    // To store indexes of result pair
        let res_l=0, res_r=0; 
  
        // Initialize left and right indexes
        // and difference between
        // pair sum and x
        let l = 0, r = n-1, diff = Number.MAX_VALUE;
  
        // While there are elements
        // between l and r
        while (r > l)
        {
            // Check if this pair is closer
            // than the closest pair so far
            if (Math.abs(arr[l] + 
                arr[r] - x) < diff)
            {
            res_l = l;
            res_r = r;
            diff = Math.abs(arr[l] + arr[r] - x);
            }
  
            // If this pair has more sum, 
            // move to smaller values.
            if (arr[l] + arr[r] > x)
            r--;
            else // Move to larger values
            l++;
        }
  
    document.write(
    " The closest pair is "+arr[res_l]+" and "+ arr[res_r]
    );
}
      
      
    // Driver program to test above function
      
        let arr = [10, 22, 28, 29, 30, 40], x = 54;
        let n = arr.length;
        printClosest(arr, n, x);        
      
  
  
// This code is contributed by sravan kumar
  
</script>


Output

 The closest pair is 22 and 30

Time Complexity: O(n), where n is the length of an Array.
Auxiliary Space: O(1)



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads