3Sum Closest

Medium

Topics
ArrayTwo PointersSorting

Given an array nums and a value target, find three integers whose sum is closest to target and return that sum.

Example 1

-102112-43
The three shaded values sum to 2, the closest reachable to 1.
Cells are the array values; the small numbers underneath are indices.
Input:  nums = [-1,2,1,-4], target = 1
Output: 2

Example 2

000102
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

  1. Sort.
  2. For each i, two-pointer over the suffix.
  3. Update the best whenever abs(sum - target) improves; move left up if the sum is below the target, right down 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 2

Complexity

  • 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 i to the last index. It must stop at n - 3 so 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 best
Asked at ByteDance Dream11
SensAI
Beta
Tap the mic to stop voice mode