{x}
blog image

3Sum Closest

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 Explanation: 3Sum Closest

This problem asks us to find three numbers in a given array whose sum is closest to a target value. The most efficient approach involves sorting the array and then using a two-pointer technique.

Algorithm:

  1. Sort the array: Sorting allows us to efficiently find combinations that are close to the target using two pointers. We sort the input nums array in ascending order.

  2. Iterate and use Two Pointers: We iterate through the sorted array using a single loop. For each element nums[i], we use two pointers, j and k, to explore the remaining elements:

    • j starts at i + 1 (the element immediately after nums[i]).
    • k starts at n - 1 (the last element of the array).
  3. Calculate the sum: In each iteration of the inner loop (controlled by j and k), we calculate the current sum: currentSum = nums[i] + nums[j] + nums[k].

  4. Update the closest sum: We compare the absolute difference between currentSum and the target with the current minimum difference. If the new difference is smaller, we update closestSum (which initially holds a very large value) and minDiff.

  5. Adjust pointers: Based on the relationship between currentSum and target:

    • If currentSum is less than target, we increment j to consider a larger number.
    • If currentSum is greater than target, we decrement k to consider a smaller number.
    • If currentSum equals target, we've found the exact match, and we return target.
  6. Return the closest sum: After iterating through all possible combinations, we return closestSum, which holds the sum of the three numbers closest to the target.

Time and Space Complexity:

  • Time Complexity: O(n^2) - This is dominated by the nested loops. The sorting step takes O(n log n), but this is asymptotically less significant than the O(n^2) from the nested loops.
  • Space Complexity: O(log n) - This is due to the space used by the sorting algorithm (if using merge sort or quicksort, which are common implementations). In-place sorting algorithms would have O(1) space complexity.

Code Examples (with detailed comments):

The code examples provided in the original response cover multiple languages (Python, Java, C++, Go, TypeScript, JavaScript, C#, PHP). The structure is consistent across all languages. Here's a commented Python example to illustrate the key parts:

class Solution:
    def threeSumClosest(self, nums: List[int], target: int) -> int:
        # Sort the input array
        nums.sort()
        n = len(nums)
 
        # Initialize closest sum and minimum difference (a large value initially)
        closestSum = float('inf')  
        minDiff = float('inf')
 
        for i in range(n - 2):  # Iterate until the third-to-last element
            j = i + 1
            k = n - 1
 
            while j < k:  # Two-pointer approach
                currentSum = nums[i] + nums[j] + nums[k]
                diff = abs(currentSum - target)
 
                # Update if a closer sum is found
                if diff < minDiff:
                    minDiff = diff
                    closestSum = currentSum
 
                # Adjust pointers based on the current sum
                if currentSum < target:
                    j += 1
                elif currentSum > target:
                    k -= 1
                else:  # Exact match found
                    return target
 
        return closestSum  # Return the closest sum found

The other language examples follow the same logic, adapting the syntax and libraries as needed. The core algorithm remains consistent to achieve an efficient O(n^2) time complexity solution.