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.
For example:
nums = [-1, 2, 1, -4], target = 1
What is the closest sum to the target? In this case, the output is 2
because -1 + 2 + 1 = 2
.
Here is another example:
nums = [0, 0, 0], target = 1
What is the closest sum to the target? In this case, the output is 0
because 0 + 0 + 0 = 0
.
Consider the constraints:
3 <= nums.length <= 500
-1000 <= nums[i] <= 1000
-10^4 <= target <= 10^4
How would you approach solving this problem efficiently, considering both time and space complexity?
When 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:
The brute force approach to the 3Sum Closest problem is all about trying absolutely every possible combination of three numbers from the given set. We will calculate the sum of each combination and then compare it to our target value. The goal is to find the sum that is closest to the target, even if it's not an exact match.
Here's how the algorithm would work step-by-step:
def three_sum_closest_brute_force(numbers, target):
closest_sum = float('inf')
min_difference = float('inf')
# Iterate through all possible combinations of three numbers
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]
# Check if the current sum is closer to the target than the closest sum found so far
current_difference = abs(current_sum - target)
# Update the closest sum if the current difference is smaller
if current_difference < min_difference:
min_difference = current_difference
# The closest sum needs to be updated
closest_sum = current_sum
return closest_sum
The goal is to find three numbers in a list that add up to a value closest to a target number. Instead of checking every possible combination of three numbers, we'll use a more strategic approach to quickly narrow down the possibilities and find the closest sum.
Here's how the algorithm would work step-by-step:
def threeSumClosest(numbers, target):
numbers.sort()
closest_sum = float('inf')
for i in range(len(numbers) - 2):
# Avoid duplicate calculations by skipping same values.
if i > 0 and numbers[i] == numbers[i - 1]:
continue
left_pointer = i + 1
right_pointer = len(numbers) - 1
while left_pointer < right_pointer:
current_sum = numbers[i] + numbers[left_pointer] + numbers[right_pointer]
# Update closest_sum if current_sum is closer to target.
if abs(current_sum - target) < abs(closest_sum - target):
closest_sum = current_sum
if current_sum < target:
# Need a larger sum, move left pointer to the right.
left_pointer += 1
elif current_sum > target:
# Need a smaller sum, move right pointer to the left.
right_pointer -= 1
else:
# Exact match found, the closest possible.
return target
return closest_sum
Case | How to Handle |
---|---|
Null or empty input array | Return null or throw an IllegalArgumentException as there are no triplets to sum. |
Input array with fewer than 3 elements | Return null or throw an IllegalArgumentException as three numbers are required for a sum. |
Integer overflow when summing three large integers | Use a larger data type (long) to store the sum to prevent overflow. |
Array contains duplicate numbers | The sorting approach inherently handles duplicates correctly as they are adjacent and will be processed in the loops without special consideration. |
All numbers in the array are the same | The algorithm should still correctly calculate the sum of any three identical numbers and compare it to the target. |
Array contains only negative numbers | The algorithm will correctly find the closest sum to the target, even if all numbers are negative. |
Large input array with a wide range of integer values | Sorting ensures the algorithm has O(n log n) complexity, maintaining efficiency even with a large input size. |
Target value is significantly larger or smaller than any possible sum of triplets | The algorithm will still find the triplet sum closest to the target, even if the difference is very large. |