File: find-closest-number-to-zero/solution.py

Date: 2026-06-06

Time: 16:36

find-closest-number-to-zero/solution.py

Purpose

This file solves LeetCode 2239 — Find Closest Number to Zero. It's one of hundreds of standardized solution modules in the leetcode-implementations repo, each owning a single problem's algorithm.

Key Components

robot_instructions(nums: list[int]) -> int — The sole public function. Despite the misleading name (should be something like findClosestNumber), it implements the correct algorithm: find the element in nums with the smallest absolute value, breaking ties by preferring the positive number.

The contract:

Patterns

Linear scan with running best. The function initializes best to nums[0], then iterates through the rest. The update condition on line 14 is a two-part predicate:

1. abs(num) < abs(best) — strictly closer to zero, or

2. abs(num) == abs(best) and num > best — same distance but larger value (i.e., positive wins over negative)

This is the standard "argmin with tiebreaker" idiom. No sorting, no extra data structures — O(n) time, O(1) space.

Dependencies

Imports: None. Pure standalone function.

Imported by: The "Imported By" list is misleading — it shows ~400+ test files, which means this function name (robotinstructions) is the shared export convention across *all* solution modules, not that these tests actually test this specific solution. The real consumer is find-closest-number-to-zero/testsolution.py.

Flow

1. Seed best with the first element.

2. For each remaining element, check if it's strictly closer to zero, or tied but positive.

3. Return best after a single pass.

Invariants

Error Handling

None. The function trusts its caller to provide a non-empty list of integers, consistent with LeetCode's guarantees. An empty list would crash at nums[0].