3Sum Closest — LeetCode 16 Python Solution

MediumArrayTwo PointersSorting
Problem
#16
Reading time
3 min

The problem

Given an integer array nums of length n and an integer target, find three integers at distinct indices in nums such that the sum is closest to target. Return the sum of the three integers.

Example

Input
nums = [-1,2,1,-4], target = 1
Output
2
Explanation
The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

Python solution

Python
class Solution:
    def threeSumClosest(self, nums: List[int], target: int) -> int:
        nums.sort()
        n = len(nums)
        ans = inf
        for i, v in enumerate(nums):
            j, k = i + 1, n - 1
            while j < k:
                t = v + nums[j] + nums[k]
                if t == target:
                    return t
                if abs(t - target) < abs(ans - target):
                    ans = t
                if t > target:
                    k -= 1
                else:
                    j += 1
        return ans

Complexity

MeasureComplexity
TimeO(n^2)
SpaceO(\log n) auxiliary

Pattern: Two Pointers

Use the order already in the input to discard half the search space at every step. LeetCode 16. 3Sum Closest is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Two Pointers.

The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 16. 3Sum Closest?
LeetCode 16. 3Sum Closest is rated Medium on LeetCode.
What is the time complexity of LeetCode 16. 3Sum Closest?
The Python solution on this page runs in O(n^2).
What is the space complexity of LeetCode 16. 3Sum Closest?
The Python solution on this page uses O(\log n) auxiliary space.
What topics does LeetCode 16. 3Sum Closest cover?
LeetCode 16. 3Sum Closest is tagged Array, Two Pointers and Sorting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview