3Sum Closest Problem
Description
LeetCode Problem 16.
Given an integer array nums of length n and an integer target, find three integers in nums such that the sum is closest to target.
Return the sum of the three integers.
You may assume that each input would have exactly one solution.
Example 1:
Input: nums = [-1,2,1,-4], target = 1
Output: 2
Explanation: The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
Example 2:
Input: nums = [0,0,0], target = 1
Output: 0
Constraints:
- 3 <= nums.length <= 1000
- -1000 <= nums[i] <= 1000
- -10^4 <= target <= 10^4
Solution
Approach: Sort + Two Pointers
Checking every triple takes O(n3) time. After sorting, we can fix the first number and move two pointers over the rest, which tells us in which direction a closer sum lies.
- Sort
numsand start withclosest= the sum of the first three numbers (any real triple works as a starting value). - For each index
i, putleft = i + 1andrightat the last index. - While
left < right, computetotal = nums[i] + nums[left] + nums[right]and keep it asclosestif it is nearer totarget. Then:total < target: moveleftright to make the sum bigger.total > target: moverightleft to make the sum smaller.total == target: no sum can be closer, so return it right away.
Why skipping is safe: if total < target, every other partner left for nums[left] is at most nums[right], so it gives a sum that is no bigger and therefore no closer to target; nums[left] is done for this i. The same argument in mirror form applies when total > target.
A common mistake is starting closest at a large sentinel such as INT_MAX: closest - target can then overflow. Using a real sum avoids that.
Complexity: O(n2) time, where n is the length of nums (the O(n log n) sort plus one O(n) pass per fixed index), and O(1) extra space apart from the sort.
class Solution:
def threeSumClosest(self, nums: List[int], target: int) -> int:
nums.sort()
n = len(nums)
closest = nums[0] + nums[1] + nums[2]
for i in range(n - 2):
left, right = i + 1, n - 1
while left < right:
total = nums[i] + nums[left] + nums[right]
if abs(total - target) < abs(closest - target):
closest = total
if total < target:
left += 1 # need a bigger sum
elif total > target:
right -= 1 # need a smaller sum
else:
return total # an exact match cannot be beaten
return closest
Now write it from memory
Close the write-up and solve it yourself against the tests.