SDE & MLE Prep

16. 3Sum Closest

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