Three Sum Closest | Practice | GeeksforGeeks

Given an array Arr of N numbers and another number target, find three integers in the array such that the sum is closest to target. Return the sum of the three integers.
Example 1:
Input:
N = 6, target = 2
A[] = {-7,9,8,3,1,1}
Output: 2
Explanation: There is one triplet with sum
2 in the array. Triplet elements are -7,8,
1 whose sum is 2.

Example 2:
Input:
N = 4, target = 13
A[] = {5,2,7,5}
Output: 14
Explanation: There is one triplet with sum
12 and other with sum 14 in the array.
Triplet elements are 5, 2, 5 and 2, 7, 5
respectively. Since abs(13-12) ==
abs(13-14) maximum triplet sum will be
preferred i.e 14.
Your Task:
Complete threeSumClosest() function and return the expected answer.
NOTE: If their exists more than one answer then return the maximum sum.
Expected Time Complexity: O(N*N).
Expected Auxiliary Space: O(1).
Constraints:
3 ≤ N ≤ 103
-105 ≤ A[i] ≤ 105
1 ≤ target ≤ 105
0
trivedipranjal02
This comment was deleted.
0
gauravrastogi4 weeks ago
this is easy ?
0
patelneer4031 month ago
 int i,diff1=10000,diff2=100000,end,start,sum;       sort(arr.begin(),arr.end());       int n=arr.size();       for(i=0;i<n;i++)       {           start=i+1;           end=n-1;                      while(start<end)           {               sum=arr[i]+arr[start]+arr[end];                              if(sum==target)               return sum;                              else if(sum>target){                                      end--;                   diff1=min(diff1,sum-target);               }                              else if(sum<target){                                      start++;                   diff2=min(diff2,target-sum);               }                          }                             }              if(diff1 < diff2)       return target+diff1;              if(diff1==diff2)       return target+diff1;
       return target-diff2;          }
+1
akkeshri140420012 months ago
int threeSumClosest(vector<int> arr, int target) {
       // Your code goes here
       int mini=INT_MAX;
       sort(arr.begin(),arr.end());
       int m=0;
       for(int i=0;i<arr.size();i++){
           int j=i+1;
           int k=arr.size()-1;
           while(j<k){
               if(arr[i]+arr[j]+arr[k]==target){
                   return target;
               }
               else if(arr[i]+arr[j]+arr[k]<target){
                   int len=abs((arr[i]+arr[j]+arr[k])-target);
                   if(mini>len){
                       mini=len;
                       m=arr[i]+arr[j]+arr[k];
                   }
                   j++;
               }
               else{
                   int len=abs((arr[i]+arr[j]+arr[k])-target);
                   if(mini>=len){
                       mini=len;
                       m=arr[i]+arr[j]+arr[k];
                   }
                   k--;
               }
           }
       }
       return m;
       
   }
0
jswxingyu12 months ago
Python solution
class Solution:
    def threeSumClosest (self, arr, target):
    # Your Code Here
        arr.sort()
        N = len(arr)
        Sum = 1e10
        for i in range(N-2):
            a = arr[i]
            L = i + 1
            R = N - 1
            while L < R:
                temp = a+arr[L]+arr[R]
                if temp == target:
                    return target
                elif temp > target:
                    R -= 1
                else:
                    L += 1
                
                if abs(temp - target) < abs(Sum - target):
                    Sum = temp
                elif abs(temp - target) == abs(Sum - target) and temp > Sum:
                    Sum = temp      # record the bigger one
                    
        return Sum
0
soumik8672 months ago
int threeSumClosest(vector<int> arr, int target) {       sort(arr.begin(),arr.end());       int ans=INT_MAX;       for(int i=0;i<arr.size();i++){           int x=0,y=arr.size()-1;           int z=arr[i];           while(y>x){              if(x==i){                  x++;                  continue;              }              if(y==i){                  y--;                  continue;              }              if(z+arr[x]+arr[y]==target){                  return target;              }              if(abs(target-ans)>abs(target-(z+arr[x]+arr[y]))){                  ans=z+arr[x]+arr[y];              }else if(abs(target-ans)==abs(target-(z+arr[x]+arr[y]))){                  ans=max(z+arr[x]+arr[y],ans);              }              if(z+arr[x]+arr[y]>target){                  y--;              }else{                  x++;              }           }       }       return ans;   }
0
mohammedhashimb190253cs2 months ago
How does the space complexity is O(1)?
we are clearly using most efficient sorting algorithms like merge sort or quick sort which take O(N) space complexity.
Correct me if I'm wrong...
-1
parul7003 months ago
class Solution{ public:   int threeSumClosest(vector<int> arr, int target) {   int i,j,k,sum;   int n=arr.size(),closestsum=INT_MAX;    sort(arr.begin(),arr.end());    for(i=0;i<n-2;i++)   {     j=i+1; k=n-1;       while(j<k)       {       sum=arr[i]+arr[j]+arr[k];            if(sum==target)            return sum;   if(abs(target-sum)<abs(target-closestsum))                closestsum=sum; if(abs(target-sum)==abs(target-closestsum))                closestsum=max(sum,closestsum);                             if(sum<target)            j++;         else             k--;        }           }  return closestsum;   }       };
0
harshshukla30983 months ago
  int  n=array.length;     int i=0;       long sum=0;       Arrays.sort(array);       long closesum=Integer.MAX_VALUE;              for( i=0;i<n-2;i++){           int start=1+i,end=n-1;                      while(start<end){                          sum=array[i]+array[start]+array[end];           if(Math.abs(target-sum)<Math.abs(target-closesum)){               closesum=sum;           }              // System.out.print(closesum);               //closesum=;                 if(Math.abs(target-sum)==Math.abs(target-closesum)){                                      closesum=Math.max(closesum,sum);                 }                       if(target>sum){               start++;              // System.out.print(start);           }           else{           end --;           }       } }       return  (int)closesum;
sumbtied by kouslendra and piyush 
+1
ankitsinha1112004 months ago
class Solution{
  public:
    int threeSumClosest(vector<int> arr, int target) {
      sort(arr.begin(),arr.end());
      int i,j,k,d=INT_MAX,s=target,n=arr.size();
      for(i=0;i<n-1;i++)
      {
          j=i+1; k=n-1;
          while(j<k)
          {
              if(arr[i]+arr[j]+arr[k]==target)
              return target;
              else if(arr[i]+arr[j]+arr[k]<target)
              {
                  if(d>abs(target-arr[i]-arr[j]-arr[k]))
                  {
                      d=abs(target-arr[i]-arr[j]-arr[k]);
                      s=arr[i]+arr[j]+arr[k];
                  }
                  j++;
              }
              else
              {
                  if(d>=abs(target-arr[i]-arr[j]-arr[k]))
                  {
                      d=abs(target-arr[i]-arr[j]-arr[k]);
                      s=arr[i]+arr[j]+arr[k];
                  }
                  k--;
              }
          }
      }
       return s; 
    }
};
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.