Back to Problem
Official 1304 views

Editorial: 3Sum Closest

by admin ·

24

1 Intuition

After sorting, two pointers can scan all useful pairs for each fixed first element.

2 Approach

Fix i, then move lo/hi inward: increase lo when the sum is too small, decrease hi when too large, tracking the closest sum.

3 Complexity Analysis

Time O(n²), Space O(1) besides sorting.

4 Solution Code

class Solution:
    def threeSumClosest(self, nums: list[int], target: int) -> int:
        nums = sorted(nums)
        best = nums[0] + nums[1] + nums[2]
        for i in range(len(nums) - 2):
            lo, hi = i + 1, len(nums) - 1
            while lo < hi:
                s = nums[i] + nums[lo] + nums[hi]
                if abs(s - target) < abs(best - target):
                    best = s
                if s < target:
                    lo += 1
                elif s > target:
                    hi -= 1
                else:
                    return s
        return best

5 Code Walkthrough

The reference solution below implements the approach step by step.