3Sum Closest (LeetCode 16): Solution and Explanation

Medium
Array
Two Pointers
Sorting

Pick three numbers at different indices so that their sum lands as close as possible to a target, and return that sum.

Intuition

Trying every triple is O(n^3). The trick from 3Sum still applies: after sorting, fixing one number turns the rest into a two-pointer search over pairs.

With the anchor nums[i] fixed and pointers lo and hi at the two ends of the remaining range, the sum tells you which way to move. If it is below the target, only a bigger nums[lo] can bring it closer, so move lo right. If it is above, move hi left.

Each move throws away pairs that cannot beat what you have already seen for this anchor, so one sweep per anchor checks every useful pair.

Unlike 3Sum, you are not looking for an exact value, so record the sum with the smallest gap |s - target| at every step. If a sum hits the target exactly, nothing can be closer and you can return at once.

Approach: Sort and sweep two pointers

  1. Sort nums. Set best = nums[0] + nums[1] + nums[2].
  2. For each anchor i from 0 to n - 3, set lo = i + 1 and hi = n - 1.
  3. While lo < hi, compute s = nums[i] + nums[lo] + nums[hi]. If |s - target| < |best - target|, set best = s.
  4. If s < target, move lo right. If s > target, move hi left. If they are equal, return s.
  5. After every anchor is swept, return best.

Step-by-step example

nums = [-1,2,1,-4], target = 1
  1. Sort to [-4, -1, 1, 2]. Start with best = -4 + -1 + 1 = -4, which is 5 away from 1.
  2. Anchor i = 0 (-4): lo = 1, hi = 3 gives -4 + -1 + 2 = -3, 4 away, so best = -3. It is below 1, so lo moves to 2: -4 + 1 + 2 = -1, 2 away, so best = -1. lo meets hi.
  3. Anchor i = 1 (-1): lo = 2, hi = 3 gives -1 + 1 + 2 = 2, only 1 away, so best = 2. It is above 1, so hi moves left and the pointers meet.
  4. No anchors remain, so the answer is 2.

Code: Python, Java, C++

1class Solution:
2    def threeSumClosest(self, nums: List[int], target: int) -> int:
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
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n^2)

Sorting is O(n log n). Each of the n - 2 anchors runs one sweep of at most n steps.

Space

O(1)

Only a few indices and the best sum are stored, apart from whatever the sort uses internally.

Other approaches

Brute force over all triples (time O(n^3), space O(1))

Three nested loops compute every sum and keep the closest. Correct and simple, but too slow for n = 500 in many languages.

Anchor plus binary search (time O(n^2 log n), space O(1))

Fix two numbers and binary search the sorted array for the value that brings the sum nearest the target. Works, but is slower than the two-pointer sweep.

Common mistakes

  • Starting best at a huge sentinel like Integer.MAX_VALUE and then computing best - target, which overflows. Starting from a real triple avoids that.
  • Comparing sums instead of distances: the closest sum may be above or below the target, so compare |s - target|.
  • Forgetting to sort first, which breaks the logic of moving the pointers.
  • Letting lo start at i instead of i + 1, which reuses the anchor.

Frequently asked questions

Do I need to skip duplicate values like in 3Sum?

No. Skipping duplicates only saves time here, because the answer is a single sum, not a list of distinct triples. The plain sweep is already O(n^2).

Why is it safe to move only one pointer each step?

If the sum is too small, every pair using the current lo with a smaller hi would be even smaller, so none of them can be closer. Moving lo right discards exactly those pairs. The argument mirrors for a sum that is too large.

Can I stop early?

Yes, when a sum equals the target, since the distance is already zero.