Given a sorted array and a number x, find a pair in 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

A simple solution is to consider every pair and keep track of closest pair (absolute difference between pair sum and x is minimum). Finally, print the closest pair. Time complexity of this solution is O(n^{2})

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++

`// 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; ` `}` |

*chevron_right*

*filter_none*

## 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 cloest 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*/` |

*chevron_right*

*filter_none*

## 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 ` |

*chevron_right*

*filter_none*

## C#

`// C# program to find pair with sum closest to x ` `using` `System; ` ` ` `class` `GFG { ` ` ` ` ` `// Prints the pair with sum cloest 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. ` |

*chevron_right*

*filter_none*

## 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. ` `?> ` |

*chevron_right*

*filter_none*

**Output:**

The closest pair is 22 and 30

This article is contributed by **Harsh**. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the **DSA Self Paced Course** at a student-friendly price and become industry ready.

## Recommended Posts:

- Given an absolute sorted array and a number K, find the pair whose sum is K
- Find the closest pair from two sorted arrays
- Find a triplet in an array whose sum is closest to a given number
- Given a sorted and rotated array, find if there is a pair with a given sum
- Find three closest elements from given three sorted arrays
- Closest pair in an Array such that one number is multiple of the other
- Two elements whose sum is closest to zero
- Subarray whose sum is closest to K
- Subarray whose absolute sum is closest to K
- Closest product pair in an array
- Number of indices pair such that element pair sum from first Array is greater than second Array
- Pair with given product | Set 1 (Find if any pair exists)
- Find the Sub-array with sum closest to 0
- Count pairs from two sorted arrays whose sum is equal to a given value x
- Count quadruples from four sorted arrays whose sum is equal to a given value x
- Find the Kth pair in ordered list of all possible sorted pairs of the Array
- Pair formation such that maximum pair sum is minimized
- Find closest number in array
- Count pairs in a sorted array whose sum is less than x
- Check if a sorted array can be divided in pairs whose sum is k