Python 0016.py
class Solution:
def threeSumClosest(self, nums: List[int], target: int) -> int:
nums.sort()
max1 = nums[len(nums) - 1]
max2 = nums[len(nums) - 2]
limit = 10**5
high = +limit
low = -limit
for i in range(len(nums)):
# optimization
if nums[i] + max2 + max1 <= low:
continue
for j in range(i+1, len(nums)):
# optimization
if nums[i] + nums[j] + max1 <= low:
continue
for k in range(j+1, len(nums)):
sum = nums[i] + nums[j] + nums[k]
if high > sum and sum >= target:
high = sum
if low < sum and sum <= target:
low = sum
# optimization
if sum >= target:
break
diffHigh = abs(high - target)
diffLow = abs(low - target)
if diffHigh < diffLow:
return high
else:
return low
Difficulty
and has an acceptance rate of about 49% (3+ million submissions).
Typical patterns to solve this problem:
- Array
- Sorting
- Two Pointers
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation solves the “three-sum closest” problem: given an integer array nums and a target value target, it returns the sum of three distinct elements whose total is nearest to target. The algorithm begins by sorting the input, then iterates through all possible triples using three nested loops. Throughout the loops it maintains two candidate sums-high and low-that bound the target from above and below, respectively. After the enumeration finishes, the function selects the candidate whose absolute difference to target is smaller.
Key Steps
The first logical step is to sort the array, which enables early termination checks later in the loops.
nums.sort()
The algorithm records the two largest values in the sorted list for use in pruning.
max1 = nums[len(nums) - 1]
max2 = nums[len(nums) - 2]
Two sentinel variables, high and low, are initialized to extreme values that will be tightened as better candidates are discovered.
limit = 10**5
high = +limit
low = -limit
The outermost loop selects the first element of the triple.
for i in range(len(nums)):
# optimization
if nums[i] + max2 + max1 <= low:
continue
Inside the outer loop, the second loop picks the middle element.
for j in range(i+1, len(nums)):
# optimization
if nums[i] + nums[j] + max1 <= low:
continue
The innermost loop chooses the third element and computes the current sum.
for k in range(j+1, len(nums)):
sum = nums[i] + nums[j] + nums[k]
if high > sum and sum >= target:
high = sum
if low < sum and sum <= target:
low = sum
# optimization
if sum >= target:
break
After all triples have been examined, the algorithm compares the distances of high and low from the target and returns the closer one.
diffHigh = abs(high - target)
diffLow = abs(low - target)
if diffHigh < diffLow:
return high
else:
return low
Edge Cases Handled
When the array contains fewer than three elements, the loops never execute, leaving high and low at their sentinel values. The final comparison still yields a deterministic result based on the initial limits.
If all possible triples produce sums that are either all greater than or all less than the target, the pruning conditions (if nums[i] + max2 + max1 <= low and if nums[i] + nums[j] + max1 <= low) ensure that the algorithm does not discard any viable candidate, because low will be updated only when a sum not exceeding the target is found.
The inner break (if sum >= target: break) handles the situation where the current sum meets or exceeds the target; because the array is sorted, any subsequent k values would only increase the sum, so the loop can safely stop without missing a closer lower bound.
The use of max1 and max2 guarantees that the algorithm correctly evaluates the maximum possible sum for any given i or j, which is essential when the target is far larger than any achievable sum.
Performance Optimizations
The most noticeable optimization is the early-exit checks that skip entire iterations of the outer loops. By comparing the current partial sum with the best lower bound (low), the code avoids exploring triples that cannot improve the result.
if nums[i] + max2 + max1 <= low:
continue
and
if nums[i] + nums[j] + max1 <= low:
continue
These conditions rely on the sorted order and the pre-computed maximum elements to quickly determine that any continuation would stay below the current best lower bound, allowing the loops to move on.
Within the innermost loop, the break statement
if sum >= target:
break
leverages the monotonic increase of the sum as k advances. Once the sum reaches or exceeds the target, further increments of k can only produce larger sums, which would not improve the lower-bound candidate and would be unnecessary for the upper-bound candidate because high is already being updated when a sum is greater than or equal to the target but still less than the current high.
The initialization of high and low with a large positive and negative sentinel (10**5) provides a simple bound that does not require additional data structures, keeping the memory footprint minimal.
Overall, the combination of sorting, pre-computed maximum values, and conditional skips reduces the number of examined triples compared with a naïve triple-nested enumeration, leading to a more efficient execution while preserving correctness.
ELI5 - Simplified Explanation
Imagine a big box filled with numbered blocks. The goal is to pick three of these blocks and add their numbers together. You want the total to be as close as possible to a special number called the target.
First, all the blocks are lined up from smallest to largest so they are easy to look at. Think of this like putting your toys in a neat row. Two extra large numbers from the end of the row are held aside to help make quick guesses later.
The computer starts a game of hide and seek with these blocks. It uses three tiny helpers to pick different blocks one by one. The helpers go through the line and try out all sorts of combinations. Every time they pick three blocks, they add up the numbers to see what they get.
Sometimes, the helpers know right away that a group of blocks will be too small to be the answer, so they skip those ones to save time. Other times, if they find a group that is already big enough, they move on to look at others. They keep track of two special values throughout the game. One value is the smallest total they found that is still bigger than the target, and the other is the largest total they found that is smaller than the target.
Once all the combinations have been checked, the helpers compare these two special values. They figure out which one is closer to the target number, almost like measuring how many short hops it takes to reach a finish line.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||||||||
| www | AlgoMonster | Python | C++ | Java | TS | |||||||||
| WalkCCC | Python | C++ | Java | |||||||||||
| leetcode.ca | Python | C++ | C# | JS | C | Java | Go | PHP | TS | |||||
| LeetcodeHelp | Python | C++ | Java | |||||||||||
| MemoryLimitExceeded | Python | C++ | ||||||||||||
| Progiez | Python | C++ | Java | |||||||||||
| github | aylei | Rust | ||||||||||||
| begeekmyfriend | C | |||||||||||||
| BigEggStudy | C# | |||||||||||||
| chandansgowda | Python | |||||||||||||
| everthis | JS | |||||||||||||
| fartem | Ruby | |||||||||||||
| fengvyi | C++ | |||||||||||||
| gaosq0604 | Python | |||||||||||||
| Garvit244 | Python | |||||||||||||
| halfrost | Go | |||||||||||||
| JoshCrozier | JS | |||||||||||||
| linouk23 | C++ | |||||||||||||
| lkwq007 | Python | |||||||||||||
| MacJim | C++ | |||||||||||||
| martianoff | Scala | |||||||||||||
| qiyuangong | Python | |||||||||||||
| Shamik07 | Dart | |||||||||||||
| shreymehul | C# | |||||||||||||
| sonugiri1043 | C++ | |||||||||||||
| suxrobGM | C# | |||||||||||||
| vli02 | C | |||||||||||||
| vthwang | Java | |||||||||||||
| wisdompeak | C++ | |||||||||||||
| YuriSpiridonov | Python | |||||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||||||
| WalkCCC | C++, Python, Java | |||||||||||||
| leetcode.ca | C, C++, C#, Go, Java, JavaScript, PHP, Python, TypeScript | |||||||||||||
| LeetcodeHelp | C++, Java, Python | |||||||||||||
| MemoryLimitExceeded | Python, C++ | |||||||||||||
| Progiez | C++, Java, Python | |||||||||||||
| aylei | Rust | |||||||||||||
| begeekmyfriend | C | |||||||||||||
| BigEggStudy | C# | |||||||||||||
| chandansgowda | Python | |||||||||||||
| everthis | JavaScript | |||||||||||||
| fartem | Ruby | |||||||||||||
| fengvyi | C++ | |||||||||||||
| gaosq0604 | Python | |||||||||||||
| Garvit244 | Python | |||||||||||||
| halfrost | Go | |||||||||||||
| JoshCrozier | JavaScript | |||||||||||||
| linouk23 | C++ | |||||||||||||
| lkwq007 | Python | |||||||||||||
| MacJim | C++ | |||||||||||||
| martianoff | Scala | |||||||||||||
| qiyuangong | Python | |||||||||||||
| Shamik07 | Dart | |||||||||||||
| shreymehul | C# | |||||||||||||
| sonugiri1043 | C++ | |||||||||||||
| suxrobGM | C# | |||||||||||||
| vli02 | C | |||||||||||||
| vthwang | Java | |||||||||||||
| wisdompeak | C++ | |||||||||||||
| YuriSpiridonov | Python |
Videos
Similar Problems
- problem 15: 3Sum
- problem 259: 3Sum Smaller
Solved On The Same Day
- problem 112: Path Sum
- problem 409: Longest Palindrome
- problem 645: Set Mismatch
- problem 717: 1-bit and 2-bit Characters
- problem 2535: Difference Between Element Sum and Digit Sum of an Array
- problem 24: Swap Nodes in Pairs
- problem 113: Path Sum II
- problem 114: Flatten Binary Tree to Linked List
- problem 116: Populating Next Right Pointers in Each Node
- problem 129: Sum Root to Leaf Numbers
- problem 131: Palindrome Partitioning
- problem 137: Single Number II
- problem 162: Find Peak Element
- problem 165: Compare Version Numbers
- problem 172: Factorial Trailing Zeroes
- problem 201: Bitwise AND of Numbers Range
- problem 204: Count Primes
- problem 402: Remove K Digits
- problem 430: Flatten a Multilevel Doubly Linked List
- problem 451: Sort Characters By Frequency
- problem 539: Minimum Time Difference
- problem 583: Delete Operation for Two Strings
- problem 633: Sum of Square Numbers
- problem 648: Replace Words
- problem 650: 2 Keys Keyboard
- problem 670: Maximum Swap
- problem 786: K-th Smallest Prime Fraction
- problem 2507: Smallest Value After Replacing With Sum of Prime Factors
- problem 2523: Closest Prime Numbers in Range
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality