sagelearnai

3Sum Closest

Difficulty: Medium · Pattern: Two Pointers · LeetCode #16

Find three numbers at different indices in nums whose sum is closest to target, and return that sum. Exactly one closest sum exists.

Examples

text
nums = [-1, 2, 1, -4], target = 1  →  2    (-1 + 2 + 1)
nums = [0, 0, 0], target = 1       →  0

Hints

  1. This is 3Sum, but instead of an exact match you track the best distance.
  2. Sort, fix i, and use two pointers on the rest; move them based on whether the sum is below or above the target.

Approach

Sort. For each i, set l = i + 1 and r = n − 1. Compute s = nums[i] + nums[l] + nums[r]; update the answer if |s − target| improves. If s < target, increase it with l++; if it's larger, r--; if it's equal, return immediately. O(n²).

Complexity

Time: O(n²). Space: O(1) extra.

Python solution
def threeSumClosest(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
JavaScript solution
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;
}