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 Explanation: The sum that is closest to the target is 0. (0 + 0 + 0 = 0).
Constraints:
3 <= nums.length <= 500-1000 <= nums[i] <= 1000-104 <= target <= 104When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
Imagine you have a collection of numbered items and you need to pick three of them whose combined value is as close as possible to a specific target number. The brute force approach relies on checking every single possible combination of three items to see which group gets closest to your target.
Here's how the algorithm would work step-by-step:
def three_sum_closest(numbers, target):
closest_sum = float('inf')
# Check every possible triplet combination to evaluate all sums against the target
for first_index in range(len(numbers)):
for second_index in range(first_index + 1, len(numbers)):
for third_index in range(second_index + 1, len(numbers)):
current_sum = numbers[first_index] + numbers[second_index] + numbers[third_index]
# Update the closest sum if the current combination is closer to the target
if abs(current_sum - target) < abs(closest_sum - target):
closest_sum = current_sum
# Return the absolute closest combined total found across all checked triplets
return closest_sumTo find three numbers whose sum is as close to a target as possible, the optimal strategy starts by lining up all the numbers in numerical order. It then systematically tests combinations by anchoring one number and using two searchers moving inward from opposite ends to home in on the best possible total.
Here's how the algorithm would work step-by-step:
class Solution:
def threeSumClosest(self, nums: list[int], target: int) -> int:
nums.sort()
closest_total = nums[0] + nums[1] + nums[2]
# Sorting allows us to systematically navigate combinations and control sum direction.
for anchor_index in range(len(nums) - 2):
left_searcher = anchor_index + 1
right_searcher = len(nums) - 1
while left_searcher < right_searcher:
current_total = nums[anchor_index] + nums[left_searcher] + nums[right_searcher]
if abs(target - current_total) < abs(target - closest_total):
closest_total = current_total
# Exact match found means no other combination can possibly be closer.
if current_total == target:
return closest_total
elif current_total < target:
left_searcher += 1
else:
right_searcher -= 1
return closest_total| Case | How to Handle |
|---|---|
| Input array with fewer than three elements | The problem constraints typically guarantee at least three elements, but if not, the function should throw an invalid argument exception. |
| Array length is exactly three | The two-pointer traversal loop runs once, correctly returning the sum of these three elements without needing complex iteration. |
| Array contains all identical numbers | The sum is always three times that number, and the pointers will immediately converge after evaluating the first unique triplet combination. |
| Mixed negative and positive numbers with zeros | Sorting the array ensures that the two-pointer approach correctly moves left or right based on whether the current sum is smaller or larger than the target. |
| Integer overflow during sum calculation | Using 64-bit integer types for the sum prevents arithmetic overflow when adding extreme boundary values from the input array. |
| Multiple triplets share the exact same closest distance to the target | The algorithm updates the closest sum whenever a strictly smaller absolute difference is found, naturally retaining the first valid closest sum encountered. |
| Maximum sized inputs up to the constraint limit | An O(n log n) sorting phase followed by an O(n squared) two-pointer scan ensures the solution executes well within standard time limits. |
| Target is extremely large or extremely small compared to array elements | The directional pointer movements naturally drive the current sum as close as possible to the extreme target value regardless of initial distance. |