medium

3Sum Closest

Find the triplet in an array whose sum is closest to a target value.

1. Define the problem

3Sum Closest

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. Sort the array first, fix one element in an outer loop, then run converging two pointers on the remainder — track the closest sum found so far , moving left or right depending on whether the current sum is below or above target.

Constraints

  • 3 ≤ nums.length ≤ 500
  • -1000 ≤ numsi ≤ 1000
  • -104 ≤ target ≤ 104

Example

Inputnums = [-1, 2, 1, -4], target = 1
Output2

Explanation The sum that is closest to the target is 2 (-1 + 2 + 1 = 2).

2. Visualize the solution

Fix one element, converge two pointers, track the closest sum

Fix one element, converge two pointers, track the closest sum
Statusinit

Sort the array. Anchor at index 0 (-4). sum = -4 + -1 + 2 = -3, closer than the initial -4 — closest = -3. Move left inward.

What happens in this step

i = 0 (value -4)
left = 1 (value -1), right = 3 (value 2)
sum = -4 + -1 + 2 = -3, |sum - target| = |-3 - 1| = 4
previous closest = -4, |closest - target| = 5

4 < 5, so closest updates to -3. sum (-3) < target (1), so left moves inward from index 1 to index 2.
Step 1 of 4

Steps to visualize

  1. Sort the array so nearby values sit together.
  2. Fix the leftmost unfixed element as the anchor and set left just after it, right at the end.
  3. Track the closest sum found so far by comparing its distance from target.
  4. If the current sum is less than target, move left inward; if it is greater, move right inward.
  5. Stop the moment the sum exactly equals target, since no closer sum is possible.
3. Walk through the code

Walk through the code

Same walkthrough, now with the code. Press Next to move one step and watch which lines run.

Fix one element, converge two pointers, track the closest sum
Statusinit

Sort the array. Anchor at index 0 (-4). sum = -4 + -1 + 2 = -3, closer than the initial -4 — closest = -3. Move left inward.

What happens in this step

i = 0 (value -4)
left = 1 (value -1), right = 3 (value 2)
sum = -4 + -1 + 2 = -3, |sum - target| = |-3 - 1| = 4
previous closest = -4, |closest - target| = 5

4 < 5, so closest updates to -3. sum (-3) < target (1), so left moves inward from index 1 to index 2.
Step 1 of 4
4. Solution

Solution

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

  for (let i = 0; i < sorted.length - 2; i++) {
    let left = i + 1;
    let right = sorted.length - 1;

    while (left < right) {
      const sum = sorted[i] + sorted[left] + sorted[right];

      if (Math.abs(sum - target) < Math.abs(closest - target)) {
        closest = sum;
      }

      if (sum === target) {
        return sum;
      } else if (sum < target) {
        left++;
      } else {
        right--;
      }
    }
  }

  return closest;
}
Time
O(n^2)
Space
O(n) (for the sort)
5. Test cases

Test cases

InputExpectedCovers
nums = [-1, 2, 1, -4], target = 12example from the docstring
nums = [1, 1, 1, 1], target = 33an exact match is found, so the distance is 0
nums = [-5, -4, -3, -2, -1], target = -100-12an all-negative array with a target far outside its range
nums = [1, 1, 1], target = 1003smallest valid input: only three elements
nums = [1, 1, 1, 0], target = 1003duplicate values among the candidates
nums = [0, 2, 1, -3], target = -1-1a negative target that is hit exactly