3Sum Closest Medium 0 attempts
LeetCode ↗

3Sum Closest

Medium ArrayTwo Pointers LeetCode

You're given an integer array nums of length n along with a target value target. Pick any three numbers from nums so that their sum lands as close as possible to target, and return that sum (not the indices or the numbers themselves). The input is guaranteed to have exactly one closest-sum solution.

Input Format
Implement threeSumClosest(nums, target). Inputs below show JavaScript function arguments; there is no stdin parsing.
Output Format
Return the result described in the statement.

Sample Input and Output

Example 1 · Run Sample

Input
nums = [-1,2,1,-4]
target = 1
Output
2

Example 2

Input
nums = [0,0,0]
target = 1
Output
0
Constraints
  • 3 <= nums.length <= 500
  • -1000 <= nums[i] <= 1000
  • -10^4 <= target <= 10^4
Test Cases (2)
Case 1
Args: [[-1,2,1,-4],1] Expected: 2
Case 2
Args: [[0,0,0],1] Expected: 0

Sort the array and use a two-pointer approach similar to 3Sum. For each element, set two pointers at the remaining range and move them inward. Track the sum with the smallest absolute difference from the target.

javascript
function threeSumClosest(nums, target) {
  nums.sort((a, b) => a - b);
  let closest = nums[0] + nums[1] + nums[2];

  for (let i = 0; i < nums.length - 2; i++) {
    let left = i + 1, right = nums.length - 1;
    while (left < right) {
      const sum = nums[i] + nums[left] + nums[right];
      if (Math.abs(sum - target) < Math.abs(closest - target)) {
        closest = sum;
      }
      if (sum < target) left++;
      else if (sum > target) right--;
      else return sum;
    }
  }

  return closest;
}

Time: O(n²) Space: O(1) (ignoring sort space)

Saved in this browser only. Private to you.

JavaScript