3Sum Closest solution explained
3Sum Closest asks for the sum of three array values that lands nearest to a target. Sort the array, fix the smallest value of the triple, and run two pointers over the rest: if the current sum is too small, move the left pointer up; if it is too big, move the right pointer down, and remember whichever sum came closest. That is O(n²) time and O(1) extra space beyond the sort, against O(n³) for checking every triple.
By Evin JohnPublished 8 min read
The problem in plain words
You get a list of integers with at least three entries and a target number. Choose three entries at three different positions, add them, and compare the total with the target. Out of all such totals, return the one closest to the target. You return the sum itself, not the indexes or the values. The usual statement promises a single closest sum, so ties do not need a rule, but it is worth asking.
| Values | Target | Closest sum | Why |
|---|---|---|---|
[4, -1, 2, 7, -3] | 5 | 5 | -1 + 2 + 4 hits the target exactly |
[-5, 0, 3, 9] | 2 | 4 | -5 + 0 + 9 is 2 away; every other triple is further |
[1, 1, 1, 1] | 10 | 3 | Every triple sums to 3 |
[10, 20, 30] | 0 | 60 | Only one triple exists |
[6, -2, -2, 5, 1] | 0 | 1 | -2 + -2 + 5; a repeated value may be used once per copy |
What the interviewer wants to see
This question usually follows 3Sum or replaces it. The interviewer is checking whether you can adapt the sort-and-squeeze technique when there is no exact match to find, which means arguing why moving a pointer never skips the best answer. They also listen for how you handle the running best, how you break out early, and whether you notice that duplicates do not change correctness here, only speed.
- Return the triple, not the sum. Store the three values alongside the best sum.
- Four values instead of three. Add one more outer loop: O(n³) with the same inner sweep.
- Closest without going over. Only accept sums at or below the target, then the problem becomes a cousin of 3Sum Smaller.
- The array is huge and the values are small. Counting sort or a frequency table can replace the comparison sort; say so if values are bounded.
Brute force: every triple
Three nested loops over positions i < j < k try every triple and keep the sum with the smallest absolute difference. It is O(n³) time and constant space. It is the right thing to say first, it doubles as the reference for testing, and for an array of a few hundred values it is honestly fast enough. Interviewers will still ask for better.
def closest_triple_sum_brute(nums, target):
n = len(nums)
best = nums[0] + nums[1] + nums[2]
for i in range(n):
for j in range(i + 1, n):
for k in range(j + 1, n):
total = nums[i] + nums[j] + nums[k]
if abs(total - target) < abs(best - target):
best = total
return bestThe O(n²) approach: sort, fix one, squeeze two
- Sort the valuesOrder lets you predict which way a sum moves when a pointer moves. The answer is a sum, so losing the original positions costs nothing.
- Fix the first valueLoop
ifrom the start. The triple will usenums[i]as its smallest member. - Place two pointers
lostarts just afteri,hiat the last index. Their sum withnums[i]is the candidate. - Compare and moveUpdate the best if the candidate is closer. If the candidate is below the target, only a bigger value can help, so move
loright. If it is above, movehileft. If it equals the target, return at once. - Repeat until the pointers meetThen advance
i. Skipping aniequal to the previous one avoids repeating the same sweep.
def closest_triple_sum(nums, target):
nums = sorted(nums)
n = len(nums)
best = nums[0] + nums[1] + nums[2]
for i in range(n - 2):
if i > 0 and nums[i] == nums[i - 1]:
continue # same first value, same sweep
lo, hi = i + 1, n - 1
while lo < hi:
total = nums[i] + nums[lo] + nums[hi]
if abs(total - target) < abs(best - target):
best = total
if total < target:
lo += 1
elif total > target:
hi -= 1
else:
return total # distance 0 cannot be beaten
return bestfunction closestTripleSum(nums, target) {
const a = [...nums].sort((x, y) => x - y);
const n = a.length;
let best = a[0] + a[1] + a[2];
for (let i = 0; i < n - 2; i++) {
if (i > 0 && a[i] === a[i - 1]) continue;
let lo = i + 1;
let hi = n - 1;
while (lo < hi) {
const total = a[i] + a[lo] + a[hi];
if (Math.abs(total - target) < Math.abs(best - target)) best = total;
if (total < target) lo++;
else if (total > target) hi--;
else return total;
}
}
return best;
}Why moving a pointer never loses the answer
Suppose the sum with lo and hi is below the target. Pairing nums[lo] with any index left of hi gives an even smaller sum, which is further from the target than the one you just recorded. So every remaining pair that uses lo is no better than what you have, and dropping lo is safe. The mirror argument covers a sum above the target and dropping hi. Each step discards a whole row or column of pairs that cannot win, which is why one linear sweep per i covers all pairs.
A cheap extra speedup on sorted data: if nums[i] + nums[i+1] + nums[i+2] already exceeds the target, that is the closest sum available for this i and every later i only gets bigger, so record it and stop. If nums[i] + nums[n-2] + nums[n-1] is still below the target, record it and move to the next i without sweeping. Neither changes the worst case, but both help on skewed inputs.
Cost of each approach
| Approach | Time | Extra space |
|---|---|---|
| Every triple | O(n³) | O(1) |
| Every pair, then binary search for the third | O(n² log n) | O(1) after sorting |
| Sort, fix one, two pointers | O(n²) | O(1) after sorting (the sort itself may use O(n) or O(log n)) |
Edge cases to try
- Exactly three values: the only sum is the answer, and the loop must not read past the end.
- All values equal, such as
[1, 1, 1, 1]. - A target far below or far above every possible sum, where the answer is the smallest or largest triple.
- Negative values and a negative target.
- An exact hit early in the scan, to test the early return.
- Large magnitudes: in languages with fixed-width integers the sum of three values can overflow; Python integers and JavaScript numbers up to 2^53 are fine for typical inputs.
Mistakes that cost points
- Initializing the best to 0 or to infinity. Zero may be closer than any real sum; infinity breaks the distance math in some languages. Use the first real triple.
- Comparing the sums instead of their distances to the target.
- Moving both pointers after each step, which skips pairs.
- Sorting with JavaScript's default comparator, which orders
10before9. - Copying the 3Sum duplicate-skipping for
loandhiand getting it subtly wrong; for this problem, skipping duplicateivalues is enough.
How to explain it out loud
Fictional example
- Candidate
- The obvious answer is three loops, cubic. Since I only return a sum, I can sort, which lets me reason about which direction a sum moves.
- Candidate
- I fix the smallest member, then put one pointer after it and one at the end. If the sum is under the target, the only way to get closer is a bigger value, so the left pointer moves right. Over the target, the right pointer moves left. I keep the closest sum I have seen and return immediately on an exact match.
- Candidate
- That is n passes of a linear sweep, so quadratic time, and constant extra space apart from the sort. Let me trace the second example: with -5 fixed, 0 and 9 give 4, which is two away, and nothing later beats it.
Related problems
3Sum Smaller keeps the same sorted sweep but counts every triple under a target, which needs a different move when the sum is small. Substring with Concatenation of All Words is the other multi-pointer scan in this set, this time on words in a string. For the one-pass hash version of the pair question, see Two Sum.
Practicing it with Natively
In a practice session on a Mac or Windows computer, Natively can take a screenshot of an array problem like this one, suggest the sorted two-pointer approach with code, and point out cases you should test, such as a target far outside every possible sum. Because it also transcribes your mock interview, you can go back and check whether you justified the pointer moves or just asserted them. Read more about the AI interview assistant.
Questions people ask
How do you solve 3Sum Closest?
Sort the array, fix the first value of the triple, and move two pointers over the rest: up when the sum is below the target, down when it is above, keeping the closest sum seen. Return early on an exact match.
What is the time complexity of 3Sum Closest?
O(n²) time with the sort and two-pointer sweep, and O(1) extra space besides the sort. Checking every triple is O(n³).
Why can you sort the array in 3Sum Closest?
The answer is a sum, so positions do not matter. Sorting lets you predict which way the sum moves when a pointer moves.
How should the best sum be initialized?
Use the sum of the first three values. Starting at zero can be wrongly closer than any real triple.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
