3Sum Closest — LeetCode 16 Python Solution
- Problem
- #16
- Pattern
- Two Pointers
- Reading time
- 3 min
- Source
- leetcode.com
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
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 ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n^2) |
| Space | O(\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.