Mediumtwo-pointers
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
Tested onlyTime 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;
}
Reflection
- Which cue made you pick this pattern in under 90 seconds?
- What input would break a wrong invariant?