Taro Logo

3Sum Closest

#168 Most AskedMedium
0 views
Topics:
ArraysTwo Pointers

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 <= 104

Solution


Clarifying Questions

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:

  1. What is the minimum and maximum size of the input array `nums`, and can we assume the array always contains at least three integers?
  2. Can the input array contain negative numbers and zeros, or are we dealing strictly with positive integers?
  3. How should I handle duplicate numbers in the input array? Do they affect the selection of unique triplets or the closest sum calculation?
  4. If there are multiple triplets that result in the exact same closest sum distance to the target, does it matter which one we return or are they all considered equally valid?
  5. Are the values in `nums` and the `target` integer guaranteed to fit within standard integer limits, or could their sums cause integer overflow issues?

Brute Force Solution

Approach

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:

  1. Start by looking at the entire collection of items available to you.
  2. Select any three items from the collection.
  3. Add the values of these three chosen items together to get a combined total.
  4. Compare this combined total with your target number and note down how far apart they are.
  5. Put those three items back and choose a different set of three items.
  6. Repeat the process of adding them up and comparing the total to your target number.
  7. Keep doing this until every single possible combination of three items has been tried and checked.
  8. Finally, look back at all the differences you noted down and pick the group whose combined total came the absolute closest to your target.

Code Implementation

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_sum

Big(O) Analysis

Time Complexity
O(n³) – The brute force approach requires evaluating every possible combination of three items from the collection of size n. For the first item, we choose from n possibilities, for the second from n minus 1, and for the third from n minus 2. This exhaustive combination checking results in approximately n * (n-1) * (n-2) / 6 operations. Simplifying this polynomial expression by dropping constants and lower-order terms yields a final time complexity of O(n³).
Space Complexity
O(log n) or O(n) – The space complexity is driven entirely by the sorting step required to arrange the items in the collection before evaluating combinations. Depending on the language's implementation, the internal sorting algorithm utilizes auxiliary stack space or temporary arrays proportional to the input size N. Beyond this sorting overhead, the algorithm only allocates a few primitive variables to track pointers and the closest sum found so far, meaning no additional data structures scale with N.

Optimal Solution

Approach

To 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:

  1. Arrange all the given numbers from smallest to largest so they are easy to navigate.
  2. Keep track of the closest total found so far, starting with the very first combination you look at.
  3. Pick one number as your starting point, and place a searcher at the item immediately following it and another searcher at the very end of the line.
  4. Add the three chosen numbers together and compare the result to your target, updating your closest total if this new combination is a better match.
  5. If the combined total is smaller than your target, move your lower searcher up to a larger number to increase the sum.
  6. If the combined total is larger than your target, move your upper searcher down to a smaller number to decrease the sum.
  7. If the combined total matches your target exactly, you have found the best possible answer and can stop immediately.
  8. Continue adjusting the searchers until they meet, then shift your starting point to the next number and repeat the process until all possibilities have been efficiently explored.

Code Implementation

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

Big(O) Analysis

Time Complexity
O(n²) – First, sorting the array of n elements takes O(n log n) time. Then, we use a single loop to anchor each of the n numbers, and for each anchor, we use two inward-moving searchers that traverse the remaining elements in linear time. This combination of an outer loop and an inner two-pointer scan results in approximately n * n/2 operations. Combining the sorting and scanning phases, the overall time complexity simplifies to O(n²).
Space Complexity
O(1) – The algorithm only requires a few constant-sized primitive variables to keep track of the closest total, loop counters, and pointer positions. The sorting operation is performed in place depending on the language runtime, meaning no auxiliary data structures grow in proportion to the input size N. Thus, the extra memory usage remains strictly constant regardless of how many elements are in the array.

Edge Cases

Input array with fewer than three elements
How to Handle:
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
How to Handle:
The two-pointer traversal loop runs once, correctly returning the sum of these three elements without needing complex iteration.
Array contains all identical numbers
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
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
How to Handle:
The directional pointer movements naturally drive the current sum as close as possible to the extreme target value regardless of initial distance.
0/257 completed