3Sum Closest Medium 0 attempts
LeetCode ↗

3Sum Closest

Medium ArrayTwo Pointers LeetCode

Given an integer array nums of length n and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.

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

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.

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