16. 3Sum Closest

Given an integer array nums of length n and an integer target, find three integers at distinct indices 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

Approach 01: Sorting and Two Pointers



class Solution {
public:
    int threeSumClosest(vector& nums, int target) {
        sort(nums.begin(), nums.end());
        int closest_sum = nums[0] + nums[1] + nums[2];
        for (int i = 0; i < nums.size() - 2; i++) {
            int left = i + 1, right = nums.size() - 1;
            while (left < right) {
                int current_sum = nums[i] + nums[left] + nums[right];
                if (abs(current_sum - target) < abs(closest_sum - target)) {
                    closest_sum = current_sum;
                }
                if (current_sum < target) left++;
                else if (current_sum > target) right--;
                else return target;
            }
        }
        return closest_sum;
    }
};

Time Complexity:

  • O(n²): Outer loop runs n times, inner two-pointer loop runs O(n).

Space Complexity:

  • O(log n) to O(n): Depending on the sorting implementation.
class Solution:
    def threeSumClosest(self, nums: List[int], target: int) -> int:
        nums.sort()
        closest_sum = sum(nums[:3])
        for i in range(len(nums) - 2):
            left, right = i + 1, len(nums) - 1
            while left < right:
                current_sum = nums[i] + nums[left] + nums[right]
                if abs(current_sum - target) < abs(closest_sum - target):
                    closest_sum = current_sum
                if current_sum < target:
                    left += 1
                elif current_sum > target:
                    right -= 1
                else:
                    return target
        return closest_sum

Time Complexity:

  • O(n²): Outer loop runs n times, inner two-pointer loop runs O(n).

Space Complexity:

  • O(log n) to O(n): Depending on the sorting implementation.
class Solution {
    public int threeSumClosest(int[] nums, int target) {
        Arrays.sort(nums);
        int closestSum = nums[0] + nums[1] + nums[2];
        for (int i = 0; i < nums.length - 2; i++) {
            int left = i + 1, right = nums.length - 1;
            while (left < right) {
                int currentSum = nums[i] + nums[left] + nums[right];
                if (Math.abs(currentSum - target) < Math.abs(closestSum - target)) {
                    closestSum = currentSum;
                }
                if (currentSum < target) left++;
                else if (currentSum > target) right--;
                else return target;
            }
        }
        return closestSum;
    }
}

Time Complexity:

  • O(n²): Outer loop runs n times, inner two-pointer loop runs O(n).

Space Complexity:

  • O(log n) to O(n): Depending on the sorting implementation.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top