3Sum Closest
Medium
Topics
Given an array nums and a value target, find three integers whose sum is closest to target and return that sum.
Example 1
Input: nums = [-1,2,1,-4], target = 1 Output: 2
Example 2
Input: nums = [0,0,0], target = 1 Output: 0
Constraints
- 3 <= nums.length <= 500
- -1000 <= nums[i] <= 1000
- -10^4 <= target <= 10^4
Editorial — intuition, approach, complexity and pitfalls
Intuition
Three nested loops over all triples is O(n^3). The fix is the same one that makes 3Sum tractable: sort first, then fix one element and collapse the remaining two-sum into a two-pointer sweep.
Sorting is what makes the sweep possible. With the array ordered, a sum that is too small can only be increased by moving the left pointer right, and one that is too large only by moving the right pointer left. Each decision is forced, so the inner scan is linear rather than quadratic.
Unlike 3Sum there is no duplicate-skipping to do — we want a single closest sum, not a set of distinct triplets — so the sweep is simpler. And we track the best by absolute distance from the target rather than looking for an exact hit.
Approach
- Sort.
- For each
i, two-pointer over the suffix. - Update the best whenever
abs(sum - target)improves; moveleftup if the sum is below the target,rightdown if above, and return immediately on an exact match.
Dry Run
nums = [-1,2,1,-4], target = 1
sorted [-4,-1,1,2]
i=0 (-4): left=1 right=3 sum -4-1+2 = -3 dist 4 best -3
-3 < 1 so left++
left=2 right=3 sum -4+1+2 = -1 dist 2 best -1
-1 < 1 so left++, pointers meet
i=1 (-1): left=2 right=3 sum -1+1+2 = 2 dist 1 best 2
2 > 1 so right--, pointers meet
answer 2Complexity
- Time — O(n^2): an O(n) sweep for each of n fixed elements. The O(n log n) sort is dominated. Against O(n^3) for the triple loop.
- Space — O(log n) in Java and C++, O(n) in Python, all of it the sort: an in-place quicksort recurses, and Python's Timsort allocates a merge buffer. The sweep itself holds three indices, so "O(1) space" is the claim the sort makes false.
Common Pitfalls
- Comparing raw sums instead of distances from the target. The closest sum can be above or below it.
- Initialising the best to 0 rather than to an actual triple's sum. With all-negative input, 0 is unreachable and would be reported.
- Looping
ito the last index. It must stop atn - 3so that two more elements remain. - Skipping duplicates as in 3Sum. Harmless but unnecessary here, and it can skip the closest sum if done carelessly.
- Forgetting the early return on an exact hit — not required for correctness, but it is the one case where nothing better exists.
Full Solution — all languages
class Solution:
def threeSumClosest(self, nums, target):
nums.sort()
best = nums[0] + nums[1] + nums[2]
for i in range(len(nums) - 2):
left, right = i + 1, len(nums) - 1
while left < right:
s = nums[i] + nums[left] + nums[right]
if abs(s - target) < abs(best - target):
best = s
if s < target:
left += 1
elif s > target:
right -= 1
else:
return s
return bestimport java.util.*;
class Solution {
public int threeSumClosest(int[] nums, int target) {
Arrays.sort(nums);
int best = 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 s = nums[i] + nums[left] + nums[right];
if (Math.abs(s - target) < Math.abs(best - target)) best = s;
if (s < target) left++;
else if (s > target) right--;
else return s;
}
}
return best;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int threeSumClosest(vector<int>& nums, int target) {
sort(nums.begin(), nums.end());
int best = nums[0] + nums[1] + nums[2];
for (int i = 0; i < (int)nums.size() - 2; i++) {
int left = i + 1, right = (int)nums.size() - 1;
while (left < right) {
int s = nums[i] + nums[left] + nums[right];
if (abs(s - target) < abs(best - target)) best = s;
if (s < target) left++;
else if (s > target) right--;
else return s;
}
}
return best;
}
};/**
* @param {number[]} nums
* @param {number} target
* @return {number}
*/ var threeSumClosest = function(nums, target) {
nums.sort((a, b) => a - b);
let best = nums[0] + nums[1] + nums[2];
for (let i = 0; i < nums.length - 2; i++) {
let left = i + 1, right = nums.length - 1;
while (left < right) {
const s = nums[i] + nums[left] + nums[right];
if (Math.abs(s - target) < Math.abs(best - target)) best = s;
if (s < target) left++;
else if (s > target) right--;
else return s;
}
}
return best;
};