Skip to main content

3Sum Closest


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
  • -10^4 <= target <= 10^4

Try this Problem on your own or check similar problems:

  1. 3Sum
  2. 4Sum
Solution:
public int threeSumClosest(int[] nums, int target) {
Integer closestSum = null;
Arrays.sort(nums);

for(int i = 0; i < nums.length - 2; ++i){
int j = i + 1, k = nums.length - 1;
while(j < k){
int sum = nums[i] + nums[j] + nums[k];

if(sum == target){
return sum;
}else if (closestSum == null || Math.abs(target - closestSum) > Math.abs(target - sum)){
closestSum = sum;
}

if(sum < target){
++j;
}else{
--k;
}
}
}

return closestSum;
}

Time/Space Complexity:
  • Time Complexity: O(n^2)
  • Space Complexity: O(1)

Explanation:

We use the same two pointers approach on sorted array as we did in 3Sum only this time we don't have to remove the duplicates, we just have to check if the sum of the current triplet is closer to the target than our previous recorded value and adjust the pointers accordingly. The i only has to iterate to the 3 last element since we have to make space for j and k. We achieve the same time complexity as we did in the regular 3Sum problem.