LeetCode #16 Medium

3Sum Closest

3Sum Closest is LeetCode 16 (Medium). Given an integer array nums and an integer target, choose three numbers at different positions whose sum is as close to target as possible, and return that sum.

  • Each input has exactly one closest sum, so ties never need breaking.
  • With up to 500 numbers there are about 2 × 10⁷ triples to try one by one; sorting first brings the work down to about 125,000 sums.
Constraints
  • 3 <= nums.length <= 500
  • -1000 <= nums[i] <= 1000
  • -10⁴ <= target <= 10⁴
arraytwo-pointerssorting
Open on LeetCode ↗
02

Intuition

Sort the array and fix the first number of the triple, nums[i]. The other two come from the part to its right: lo starts at its left end and hi at its right end.

In a sorted array, comparing the sum with the target tells you which pointer to move:

  • Sum below target: move lo right, the only way to raise it. Every pair of nums[lo] with a partner left of hi is even smaller, so none of them can be closer.
  • Sum above target: move hi left, for the mirror reason.
  • Sum equal to target: distance 0 cannot be beaten, so return it.

Each move rules out only pairs that cannot win, so the closest triplet sum is never skipped.

How to spot this pattern

Pick numbers whose sum is near a value, in an array you are free to sort: fix one number and close two pointers from both ends.

03

Approach

Try it first

Before reading on, sort [-1, 2, 1, -4], fix -4 and put pointers on the next number and the last one. If their sum is below the target, which pointer can bring it closer? Aim for O(n²).

1

Sort the array

Sort nums in ascending order. Sorted order is what lets a single comparison with target decide which pointer to move.

2

Start from a real triple

Set best = nums[0] + nums[1] + nums[2]. Starting from an actual sum means there is always a valid answer to compare against, with no infinity placeholder whose distance to the target can overflow.

3

Fix one number, sweep the other two

For each i from 0 to n − 3, set lo = i + 1 and hi = n − 1. While lo < hi, compute the sum of the three and keep it as best if |sum − target| is smaller than |best − target|.

4

Move a pointer, or stop

If the sum is below target, add 1 to lo; if it is above, subtract 1 from hi. If it equals target, return it straight away.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def threeSumClosest(self, nums, target):
▶3 nums.sort()
▶4 best = nums[0] + nums[1] + nums[2]
▶5 for i in range(len(nums) - 2):
▶6 lo, hi = i + 1, len(nums) - 1
▶7 while lo < hi:
▶8 s = nums[i] + nums[lo] + nums[hi]
▶9 if abs(s - target) < abs(best - target):
▶10 best = s
▶11 if s < target:
▶12 lo += 1
▶13 elif s > target:
▶14 hi -= 1
▶15 else:
▶16 return s
▶17 return best
−40−111223−53target 1fixedlohisum++=off bybestbest off by−45sorted → best starts at −4
nums[−4, −1, 1, 2]sorted
best−4first three
Sorting puts small numbers on the left and big ones on the right, so moving a pointer has a known effect on the sum. best starts as a real triple, the first three numbers: −4 + −1 + 1 = −4, which is 5 away from 1.
−40i−11lo1223hi−53target 1fixedlohisum++=off bybestbest off by−45fix −4, pointers at both ends
i0fixed −4
lo, hi1, 3
Fix −4 as the first number. Its two partners come from the numbers to its right: lo starts at the smallest of them and hi at the largest.
−40i−11lo1223hi−53target 1sum −3fixedlohisum−4−12−3++=off bybestbest off by4−34closest so far → lo moves right
sum−3off by 4
best−3
−4 + −1 + 2 = −3, 4 away from the target. That is closer than any sum so far, so it becomes the new best. The sum is below 1. Moving hi left would only shrink it, so every pair of −1 with a smaller partner is even further away. Drop −1 by moving lo right.
−40i−1112lo23hi−53target 1sum −1fixedlohisum−412−1++=off bybestbest off by2−12closest so far → lo moves right
sum−1off by 2
best−1
−4 + 1 + 2 = −1, 2 away from the target. That is closer than any sum so far, so it becomes the new best. The sum is below 1. Moving hi left would only shrink it, so every pair of 1 with a smaller partner is even further away. Drop 1 by moving lo right.
−40−11i12lo23hi−53target 1fixedlohisum++=off bybestbest off by−12fix −1, pointers at both ends
i1fixed −1
lo, hi2, 3
Fix −1 as the first number. Its two partners come from the numbers to its right: lo starts at the smallest of them and hi at the largest.
−40−11i12lo23hi−53target 1sum 2fixedlohisum−1122++=off bybestbest off by121closest so far → hi moves left
sum2off by 1
best2
−1 + 1 + 2 = 2, 1 away from the target. That is closer than any sum so far, so it becomes the new best. The sum is above 1. Every pair of 2 with a bigger partner is even further away, so drop 2 by moving hi left.
−40−111223−53target 1fixedlohisum++=off bybestbest off by21every start tried → answer 2
answer2off by 1
Every first number has had its sweep, and each pointer move only skipped pairs that could not be closer. So 2, 1 away from 1, is the closest sum of three.
05

Common pitfalls

Comparing signed differences

✗ Wrong
if s - target < best - target:
    best = s
✓ Right
if abs(s - target) < abs(best - target):
    best = s

Without abs, a sum far below the target looks like an improvement. For [-1, 2, 1, -4] with target 1 this returns −4 instead of 2, because −4 − 1 = −5 is the smallest signed difference.

06

Edge cases

Exactly three numbers

There is only one triple. best starts as its sum, the loop runs once for i = 0 and checks the same triple again, and that sum is returned.

07

Complexity

Time
O(n²)
Space
O(1) extra (sorting may use O(log n) to O(n))
Sorting costs O(n log n). Then for each of the n − 2 choices of i, the two pointers meet after at most n steps.
08

3Sum Closest FAQ

How is this different from 3Sum?

3Sum (LeetCode 15) lists every triple that adds up to exactly 0 and must skip repeated values to avoid duplicate triples. Here only one sum is returned, so repeated values do no harm, and the scan tracks a distance instead of collecting matches.

Does skipping repeated values of nums[i] help?

It saves a little time on inputs with many duplicates, because the same first number would give the same sweep. It is optional: the answer is the same with or without it.