16. 3Sum Closest
Medium ↗ Open on LeetCode Source: Misc
Quick review
- Pattern
- Two Pointers
- Time
- —
- Space
- —
Standard Solution (C++)
SummaryGiven an integer array and a target value, find three elements whose sum is closest to the target, and return that sum. Exactly one answer is guaranteed to exist.
Approach
- Sort the array, then fix one element with an outer loop and use two pointers (lo, hi) on the remaining subarray to efficiently scan all pairs.
- At each step, compute the three-element sum and update the best answer if the current sum is closer to the target.
- If the sum exceeds the target, move the right pointer left (to decrease the sum); if it falls short, move the left pointer right (to increase it). An exact match returns immediately.
- Sorting enables the two-pointer shrink decisions and reduces the naive O(n³) search to O(n²).
#include <vector>
#include <algorithm>
#include <climits>
using namespace std;
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
sort(nums.begin(), nums.end());
int best = INT_MAX; // will hold the best sum found so far
int n = nums.size();
for (int i = 0; i < n - 2; ++i) {
int lo = i + 1, hi = n - 1;
while (lo < hi) {
int sum = nums[i] + nums[lo] + nums[hi];
// Update best if this sum is strictly closer to target
if (best == INT_MAX ||
abs(sum - target) < abs(best - target)) {
best = sum;
}
if (sum == target) return sum; // Can't do better
else if (sum < target) ++lo; // Need a larger sum
else --hi; // Need a smaller sum
}
}
return best;
}
}; Time O(n²) Space O(1)
A canonical reference solution. Problem statement © LeetCode — see the official link above.
My Solution (C++)
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
int n=nums.size();
int closetSum=nums[0]+nums[1]+nums[2];
sort(nums.begin(), nums.end());
for(int i=0; i<n-2; ++i){
int j=i+1;
int k=n-1;
while(j<k){
int curSum=nums[i]+nums[j]+nums[k];
int curDiff=curSum-target;
if(abs(curDiff)<abs(closetSum-target))
closetSum=curSum;
if(curDiff==0)
return target;
else if(curDiff>0)
k--;
else
j++;
}
}
return closetSum;
}
};
// Time: O(N^2)
// Space: O(1) My own solution and notes, as I wrote them.
▶ Run it — editable in-browser playground with a sample driver C++
Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.
C++ ▶ Runnable Auto-generated driver with sample input — unverified.
Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.