Skip to content
DSA Patterns
Menu
Language
Two PointersLC #163 of 6← PreviousNext →

Demo preview: These solutions pass the automated test suite but have not been human-reviewed. Treat trade-offs and prose as draft.

3Sum Closest

Problem (restated)

Given an integer array nums and integer target, find three integers whose sum is closest to target. Return that sum.

Intuition

Sort, fix one index, two-pointer the rest while tracking the closest sum. same structure as 3Sum.

Approaches

Sort + two pointers

Unverified
Time O(n²)Space O(1)

Idea. For each i, lo/hi scan; update best when |sum-target| improves.

Walkthrough. nums=[-1,2,1,-4], target=1 → closest sum is 2.

Trade-offs. O(n²) after sort is expected; hashing does not simplify closest-sum.

Solution
export function threeSumClosest(nums: number[], target: number): number {
  nums = [...nums].sort((a, b) => a - b);
  let best = nums[0]! + nums[1]! + nums[2]!;
  for (let i = 0; i < nums.length - 2; i++) {
    let lo = i + 1, hi = nums.length - 1;
    while (lo < hi) {
      const s = nums[i]! + nums[lo]! + nums[hi]!;
      if (Math.abs(s - target) < Math.abs(best - target)) best = s;
      if (s === target) return s;
      if (s < target) lo++; else hi--;
    }
  }
  return best;
}
export function threeSumClosest(nums: number[], target: number): number {
  nums = [...nums].sort((a, b) => a - b);
  let best = nums[0]! + nums[1]! + nums[2]!;
  for (let i = 0; i < nums.length - 2; i++) {
    let lo = i + 1, hi = nums.length - 1;
    while (lo < hi) {
      const s = nums[i]! + nums[lo]! + nums[hi]!;
      if (Math.abs(s - target) < Math.abs(best - target)) best = s;
      if (s === target) return s;
      if (s < target) lo++; else hi--;
    }
  }
  return best;
}

Template connection

The same sorted spine as 3Sum. Fix i, then move the pair. Keep the sum whose distance to target is smallest, instead of collecting exact zeros. A sum below the target moves left; a sum above it moves right.

Reflection

  • Same skeleton as 3Sum. The target is not 0, and you record the sum, not the triple.
  • Do you update abs(sum - target) on every L, R pair, or only on an exact hit?
  • Is an early return legal when sum == target?
Contributor review checklist

Interactive

Mental model

A worked animation for this problem. Scrub steps or press space to pause; re-tell the invariant out loud.

Step 1 of 6
1/6

3Sum closest to target 1. Sort first, then fix one value and two-pointer the rest.

-1
0
2
1
1
2
-4
3

target = 1

Key:CurrentLeft / slowRight / fastMatchSettled