Skip to problem
←

3Sum Closest

Medium 0 attempts

Given an integer array nums and an integer target, choose three elements at distinct indices whose sum is closest to target. Return that sum.

The closest sum is guaranteed to be unique; several choices of indices may produce the same sum.

Function contract

Implement threeSumClosest(nums, target), where nums is an integer array and target is an integer.

Output: The sum of three elements at distinct indices closest to target. The closest sum is guaranteed to be unique.

Example 1

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

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)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript