16. 3Sum Closest
Asked at 12Bloomberg61Amazon52Google51Meta50Microsoft41tcs36Infosys30Harness100Dream1168Zoho52ByteDance50Flipkart43
Problem
Pick three values from different positions in nums whose sum is as close as possible to target, and return that sum. Exactly one closest sum exists.
Example: nums = [-1,2,1,-4], target = 1 → 2 (−1 + 2 + 1)
Constraints: n ≤ 500.
Same skeleton as 3Sum: sort, fix i, two pointers on the rest; track the sum with the smallest |sum - target|.
Complexity: O(n²).
class Solution:
def threeSumClosest(self, nums: List[int], target: int) -> int:
nums.sort()
best = nums[0] + nums[1] + nums[2]
for i in range(len(nums) - 2):
l, r = i + 1, len(nums) - 1
while l < r:
s = nums[i] + nums[l] + nums[r]
if abs(s - target) < abs(best - target):
best = s
if s < target:
l += 1
elif s > target:
r -= 1
else:
return s
return best
assert Solution().threeSumClosest([-1, 2, 1, -4], 1) == 2
assert Solution().threeSumClosest([0, 0, 0], 1) == 0
class Solution {
public int threeSumClosest(int[] nums, int target) {
Arrays.sort(nums);
int best = nums[0] + nums[1] + nums[2];
for (int i = 0; i < nums.length - 2; i++) {
int l = i + 1, r = nums.length - 1;
while (l < r) {
int s = nums[i] + nums[l] + nums[r];
if (Math.abs(s - target) < Math.abs(best - target)) best = s;
if (s < target) l++;
else if (s > target) r--;
else return s;
}
}
return best;
}
}
func threeSumClosest(nums []int, target int) int {
sort.Ints(nums)
best := nums[0] + nums[1] + nums[2]
for i := 0; i < len(nums)-2; i++ {
for l, r := i+1, len(nums)-1; l < r; {
s := nums[i] + nums[l] + nums[r]
if abs(s-target) < abs(best-target) {
best = s
}
switch {
case s < target:
l++
case s > target:
r--
default:
return s
}
}
}
return best
}
func abs(x int) int {
if x < 0 {
return -x
}
return x
}