Problem 2239

Abstract / Summary

Given a list of numbers, find the one closest to zero.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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
11 lines | 324 bytes | submitted October 20, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 48% (400k+ submissions).

Typical patterns to solve this problem:
  • Array
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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 -x and x appear, the comparison result < n promotes x over -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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 7.44 | σ = 0.92

Complexity Analysis

Time: linear
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
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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
24 links | 13 authors | 8 languages

Videos

8 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

1 easy 4 medium 1 hard
7 solutions   October 20, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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