To solve this problem, we can use a combination of sorting and the two-pointer technique. Here's a step-by-step approach:
- Sort the Array: Sorting the array allows us to efficiently find the closest sum using the two-pointer technique.
- Iterate Through the Array: For each element in the array, treat it as the first element of the triplet and use the two-pointer technique to find the other two elements.
- Two-Pointer Technique: Initialize two pointers, one at the element after the current element and one at the end of the array. Move the pointers based on whether the current sum is less than or greater than the target.
- Track the Closest Sum: Keep track of the sum that is closest to the target as you iterate through the array.
Here’s the Python implementation:
def threeSumClosest(nums, target):
nums.sort() # Step 1: Sort the array
n = len(nums)
closest_sum = float('inf') # Initialize closest sum to infinity
for i in range(n - 2): # Step 2: Iterate through the array
left, right = i + 1, n - 1 # Initialize two pointers
while left < right: # Step 3: Two-pointer technique
current_sum = nums[i] + nums[left] + nums[right]
if abs(current_sum - target) < abs(closest_sum - target):
closest_sum = current_sum # Update closest sum if current sum is closer
if current_sum < target:
left += 1 # Move left pointer to increase the sum
elif current_sum > target:
right -= 1 # Move right pointer to decrease the sum
else:
return current_sum # If exact match, return immediately
return closest_sum
# Example usage:
print(threeSumClosest([-1, 2, 1, -4], 1)) # Output: 2
print(threeSumClosest([0, 0, 0], 1)) # Output: 0
Explanation:
- Sorting: Sorting the array allows us to efficiently find the closest sum using the two-pointer technique.
- Two-Pointer Technique: For each fixed element
nums[i], we use two pointers (left and right) to find the other two elements that form the closest sum to the target.
- Closest Sum Tracking: We continuously update the
closest_sum whenever we find a sum that is closer to the target than the current closest_sum.
- Early Exit: If we find a sum that exactly matches the target, we can return it immediately since it’s the closest possible sum.
This approach ensures that we efficiently find the triplet with the sum closest to the target in (O(n^2)) time complexity, where (n) is the length of the input array.