3Sum Closest

medium array two pointers sorting

Problem

Given an integer array nums and an integer target, find three integers in nums whose sum is closest to target and return their sum.

Inputnums = [-1, 2, 1, -4], target = 1
Output2
The triplet (-1, 2, 1) sums to 2, closest to target 1.

def three_sum_closest(nums, target):
    nums.sort()
    best = nums[0] + nums[1] + nums[2]
    for i in range(len(nums) - 2):
        l, r = i + 1, len(nums) - 1
        while l < r:
            s = nums[i] + nums[l] + nums[r]
            if abs(s - target) < abs(best - target):
                best = s
            if s < target: l += 1
            elif s > target: r -= 1
            else: return s
    return best
function threeSumClosest(nums, target) {
  nums.sort((a, b) => a - b);
  let best = nums[0] + nums[1] + nums[2];
  for (let i = 0; i < nums.length - 2; i++) {
    let l = i + 1, r = nums.length - 1;
    while (l < r) {
      const s = nums[i] + nums[l] + nums[r];
      if (Math.abs(s - target) < Math.abs(best - target)) best = s;
      if (s < target) l++;
      else if (s > target) r--;
      else return s;
    }
  }
  return best;
}
class Solution {
    public int threeSumClosest(int[] nums, int target) {
        Arrays.sort(nums);
        int best = nums[0] + nums[1] + nums[2];
        for (int i = 0; i < nums.length - 2; i++) {
            int l = i + 1, r = nums.length - 1;
            while (l < r) {
                int s = nums[i] + nums[l] + nums[r];
                if (Math.abs(s - target) < Math.abs(best - target)) best = s;
                if (s < target) l++;
                else if (s > target) r--;
                else return s;
            }
        }
        return best;
    }
}
int threeSumClosest(vector<int>& nums, int target) {
    sort(nums.begin(), nums.end());
    int best = nums[0] + nums[1] + nums[2];
    for (int i = 0; i < (int)nums.size() - 2; i++) {
        int l = i + 1, r = nums.size() - 1;
        while (l < r) {
            int s = nums[i] + nums[l] + nums[r];
            if (abs(s - target) < abs(best - target)) best = s;
            if (s < target) l++;
            else if (s > target) r--;
            else return s;
        }
    }
    return best;
}
Time: O(n²) Space: O(1)