MediumNo. 0016

3Sum Closest — LeetCode 16 Python Solution

Topics
Array, Two Pointers, Sorting
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

PythonSolution
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

Time
O(n2)
Space · auxiliary
O(log n)

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

Related problems
No.ProblemDifficulty
00153SumMedium
00184SumMedium
0075Sort ColorsMedium
0088Merge Sorted ArrayEasy
0475HeatersMedium
0524Longest Word in Dictionary through DeletingMedium

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(n2).

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.

Free to download. Check it runs on your machine, then pick a plan.