Python 2239.py
class Solution:
def findClosestNumber(self, nums: List[int]) -> int:
result = nums[0]
for n in nums:
if abs(result) > abs(n):
result = n
continue
if abs(result) == abs(n) and result < n:
result = n
return result
Difficulty
and has an acceptance rate of about 48% (400k+ submissions).
Typical patterns to solve this problem:
- Array
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 defines a class Solution with a single method findClosestNumber. The method receives a list of integers and returns the element whose absolute value is smallest. When two numbers share the same absolute magnitude, the method prefers the positive one (or the larger value) by returning the greater of the two. The algorithm iterates through the input once, maintaining a running candidate for the result.
Core Logic
The method begins by initializing the result with the first element of the input list. This establishes a baseline for comparison and guarantees that the function always returns a value from the original collection.
result = nums[0]
The main loop walks through each integer n in the list. For each element, the absolute value of the current result is compared to the absolute value of n.
for n in nums:
if abs(result) > abs(n):
result = n
continue
If n has a strictly smaller absolute value, it replaces result. The continue statement skips the subsequent equality check, ensuring that the tie-handling logic is only evaluated when the magnitudes are equal.
When the absolute values are identical, a secondary comparison decides which number to keep. The condition result < n selects the larger integer, which effectively chooses the positive number when the pair consists of a negative and its positive counterpart.
if abs(result) == abs(n) and result < n:
result = n
After processing all elements, the method returns the final result.
return result
Edge Cases Handled
The algorithm gracefully handles several edge conditions without additional code:
- Single-element input - The initial assignment
result = nums[0]makes the loop unnecessary, and the method returns the sole element directly. - All numbers share the same absolute value - The tie-breaking clause (
result < n) ensures that the positive version (or the larger value) is chosen, satisfying the specification for equal magnitudes. - Mixed signs with identical magnitudes - When both
-xandxappear, the comparisonresult < npromotesxover-x, delivering the expected positive result. - Zero values - Since
abs(0) == 0, any zero encountered will replace a non-zero result whose absolute value is larger. If multiple zeros exist, the first zero encountered remains, which is consistent with the tie-breaking rule because all zeros are equal.
Performance Optimizations
The implementation achieves optimal traversal efficiency by performing a single pass over the input list. Each iteration conducts only constant-time operations: two absolute value calculations, a couple of integer comparisons, and at most one assignment. By updating result immediately when a strictly better candidate is found and using continue to bypass unnecessary checks, the code avoids redundant evaluations for the majority of elements.
Because the algorithm does not allocate auxiliary data structures or invoke recursive calls, it maintains a minimal memory footprint. The in-place update of the result variable eliminates the need for additional storage, making the solution both time-efficient and space-conservative within the constraints of a single-scan approach.
ELI5 - Simplified Explanation
Imagine that a big box is filled with lots of number cards. The goal is to pick the number that is tucked closest to zero.
The computer starts by picking up the very first card from the box and holding onto it. Then, it looks at every other card one by one.
When looking at a new card, the computer checks how far it is from zero. If this new card is closer to zero than the one it is currently holding, it drops the old card and picks up the new one instead.
Sometimes, two cards are exactly the same distance from zero, like a positive five and a negative five. In that case, the computer looks to see which one is bigger. If the new card is bigger, it swaps the card it is holding for this new one.
After checking every single card in the box, the computer knows it has found the one that is closest to home base at zero.
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 | C++ | Java | Python | TS | ||||
| WalkCCC | C++ | Java | Python | ||||||
| leetcode.ca | C++ | Java | Python | Go | TS | ||||
| Progiez | C++ | Java | Python | ||||||
| github | black-shadows | C++ | |||||||
| charles-wangkai | Java | ||||||||
| fartem | Ruby | ||||||||
| fsq | C++ | ||||||||
| JoshCrozier | JS | ||||||||
| lkwq007 | Python | ||||||||
| shreymehul | C# | ||||||||
| suxrobGM | C# | ||||||||
| varunu28 | Java | ||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||
| WalkCCC | C++, Python, Java | ||||||||
| leetcode.ca | C++, Go, Java, Python, TypeScript | ||||||||
| Progiez | C++, Java, Python | ||||||||
| black-shadows | C++, C++ | ||||||||
| charles-wangkai | Java | ||||||||
| fartem | Ruby | ||||||||
| fsq | C++ | ||||||||
| JoshCrozier | JavaScript | ||||||||
| lkwq007 | Python | ||||||||
| shreymehul | C# | ||||||||
| suxrobGM | C# | ||||||||
| varunu28 | Java |
Videos
Similar Problems
- problem 658: Find K Closest Elements
Solved On The Same Day
- problem 1295: Find Numbers with Even Number of Digits
- problem 1338: Reduce Array Size to The Half
- problem 1721: Swapping Nodes in a Linked List
- problem 2149: Rearrange Array Elements by Sign
- problem 2785: Sort Vowels in a String
- problem 773: Sliding Puzzle
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