Sum Pair closest to X | Practice | GeeksforGeeks

Given a sorted array arr[] of size N and a number X, find a pair in array whose sum is closest to X.
Example 1:
Input:
N = 6, X = 54
arr[] = {10, 22, 28, 29, 30, 40}
Output: 22 30
Explanation: As 22 + 30 = 52 is closest to 54.


Example 2:
Input:
N = 5, X = 10
arr[] = {1, 2, 3, 4, 5}
Output: 4 5
Explanation: As 4 + 5 = 9 is closest to 10.

Your Task:
You don't need to read input or print anything. Your task is to complete the function sumClosest() which takes arr[] of size n and x as input parameters and returns a list containing 2 integers denoting the required pair. If multiple pairs are possible return the largest sum pair.

Expected Time Complexity: O(N)
Expected Auxiliary Space: O(1)

Constraints:
2 <= N <= 105
0 <= X <= 106
0 <= arr[i] <= 106
 
0
aniket6518gadhe1 week ago
JAVA SOLUTION
Total Time Taken:
0.62/3.02
 
int[] sumClosest(int[] arr, int x) {       int[] ans =new int[2];       int low=0,high=arr.length-1,diff=Integer.MAX_VALUE;       while(low<high){           int temp=x-(arr[low]+arr[high]);           if(diff>Math.abs(temp)){               ans[0]=arr[low];               ans[1]=arr[high];               diff=Math.abs(temp);           }           if(temp==0)               break;           if(temp>0)               low++;           if(temp<0)               high--;       }       return ans;   }
0
manishitadey191 week ago
def sumClosest(self, arr, x):       # code here       # i = 0       # j = 0       dct = {}                     for i in range(0, len(arr)-1):           for j in range(i+1, len(arr)):               dct[(arr[i], arr[j])] = arr[i] +arr[j]                      min_diff = x       res = 0              for item in dct:           if abs(x - dct[item]) < min_diff:               min_diff = abs(x - dct[item])               res = item       return res
 
for input:
24 108 
4 4 9 20 21 25 28 29 33 39 59 62 66 74 79 80 81 82 91 92 93 97 98 100
same code gives correct answer (28, 80) in the ide but gives (29,79) here, can someone tell what's the issue?
0
vickykr2 weeks ago
Java Code:-
int[] sumClosest(int[] arr, int x) {       int n=arr.length;       int i=0,s=Integer.MAX_VALUE;       int r=0,l=0,k=n-1;       while(i<k)       {                      if(mod((arr[i]+arr[k]),x)<s)           {                r=i;               l=k;               s=mod((arr[i]+arr[k]),x);           }           if(arr[i]+arr[k]==x)           {               r=i;               l=k;               break;           }           else if((arr[i]+arr[k])>x)           k--;           else           i++;                 }       int ans[]=new int[2];       ans[0]=arr[r];       ans[1]=arr[l];       return ans;          }   static int mod(int a,int b)   {       if(a>b)       return a-b;       else       return b-a;   }
0
charansaisadla2 weeks ago
Where is the error
       l=0       r=len(arr)-1       m=max(arr)       while(l<r):           if(arr[l]+arr[r]==x):               return arr[l],arr[r]                      dif=abs(arr[l]+arr[r]-x)           if dif<m:               x=arr[l]               y=arr[r]               m=min(m,dif)           if(arr[l]+arr[r]<x):               l+=1           else:               r-=1       return x,y
I am not getting answer
 
0
geminicode3 weeks ago
my approach in Python :
def sumClosest(self, arr, x):
        # code here
        
        l = 0
        h = len(arr)-1
        ans = None
        diff =99999999999
        while(l < h):
            #print(arr[l],arr[h],ans)
            if arr[l] + arr[h] == x:
                return [arr[l],arr[h]]
            elif arr[l] + arr[h] > x:
                if (arr[h] + arr[l]) - x < diff:
                    ans=[arr[l],arr[h]]
                    diff = arr[h] + arr[l] - x
                    
                h-=1
            else:
                #print(arr[l],arr[h],diff,[x - (arr[h] + arr[l])])
                if x - (arr[h] + arr[l]) < diff:
                    ans = [arr[l],arr[h]]
                    diff = x - (arr[h] + arr[l])
                l+=1
        return ans
+2
abhishektyagi12633 weeks ago
//Best Solution 
 vector<int> sumClosest(vector<int>arr, int x)   {       int s=0,e=arr.size()-1;int fir;int sec;int m=0,ans=INT_MAX,mec=0;       while(s<e){           m=arr[s]+arr[e];           if(m==x){fir=s,sec=e;break;}           else{           if(m<x){mec=x-m;}           else{mec=m-x;}           if(ans<mec){ans=mec;fir=s;sec=e;}           if(m<x){s++;}           else if(m>x){e--;}}                }       // cout<<fir<<endl; cout<<sec;       vector<int> v;       v.push_back(fir);v.push_back(sec);       return v;   }
+2
badgujarsachin833 weeks ago
 vector<int> sumClosest(vector<int>arr, int x)
    {
        int sum,di=INT_MAX;
        int first,second;
        int i=0,j=arr.size()-1;
        while(i<j){
             sum=arr[i]+arr[j];
             if(abs(sum-x)<di){
                 di=abs(sum-x);
                 first=arr[i],second=arr[j];
             }
             if(sum>x){
                 j--;
             }else{
                 i++;
             }
        }
        return {first,second};
    }
+2
mayank20211 month ago
C++ : 0.2/1.4vector<int> sumClosest(vector<int>arr, int x)   {       vector<int>v;              int i=0, j=arr.size()-1, diff=INT_MAX, one, two;              while(i<j)       {            if(arr[i]+arr[j]==x)             return {arr[i], arr[j]};                        if(abs(x-arr[i]-arr[j]) < diff)            {              diff=abs(x-arr[i]-arr[j]);              one=arr[i], two=arr[j];            }                        if(arr[i]+arr[j] > x) j--;            else i++;                  }              return {one, two};                 }
0
arunvj13jun1 month ago
class Solution {
    int[] sumClosest(int[] arr, int x) {
        int left = 0;
        int right = arr.length-1;
        int diff = Integer.MAX_VALUE;
        int sum = 0;
        int out1 = -1;
        int out2 = -1;
        
        while(left < right) {
            sum = arr[left] + arr[right];
            if(Math.abs(sum-x) < diff) {
                diff = Math.abs(sum-x);
                out1 = left;
                out2 = right;
            }
            if(sum < x) {
                left++;
            } else {
                right--;
            }
        }
        
        return new int[]{arr[out1],arr[out2]};
        
    }
}
-1
sachinupreti1901 month ago
// I m very happy , coz i didnt know that i would ever solve this question, But after wasting an hour i did it
 
class Solution{   public:   vector<int> sumClosest(vector<int>arr, int x)   {       // code here       // may be 2 pointer will use in this       int min=1000000,p,q;       vector<int>v;       vector<int>vec;       int i,l=0,r=arr.size()-1,j=0,sum;       while(l<r)       {           sum=arr[l]+arr[r];           if(sum==x)           {               v.push_back(arr[l]);               v.push_back(arr[r]);               break;                          }           if(sum<x)           {               v.push_back(arr[l]);               v.push_back(arr[r]);               l++;           }           else                               {                  v.push_back(arr[l]);               v.push_back(arr[r]);               r--;           }       }        for(i=0;i<v.size();i+=2)        {            if(abs(v[i]+v[i+1]-x) < min)            {                min=abs(v[i]+v[i+1]-x);                p=v[i];                q=v[i+1];                 }        }         vec.push_back(p);         vec.push_back(q);         return vec;          }};
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.