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 spine as 3Sum.
Approaches
Sort + two pointers
UnverifiedIdea. 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.
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
Sort + two pointers is the 3Sum spine; track the closest sum instead of collecting exact zeros.
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 everyL, Rpair, or only on an exact hit? - Is an early return legal when
sum == target?