Find Closest Number to Zero - Problem

Given an array of integers nums, your task is to find the number that has the smallest absolute distance to zero. Think of zero as the center point on a number line - you want to find which number in the array is closest to this center.

Here's the twist: if there's a tie (for example, both -3 and 3 are equally close to zero), you should return the larger positive number.

Example: In the array [-4, -2, 1, 4, 8], the number 1 is closest to zero with a distance of 1.

Tie Example: In the array [-1, 2, -1, 1], both -1 and 1 have the same distance (1) from zero, so we return 1 (the positive one).

Input & Output

example_1.py โ€” Basic Case
$ Input: nums = [-4, -2, 1, 4, 8]
โ€บ Output: 1
๐Ÿ’ก Note: The number 1 has the smallest absolute distance to zero (|1| = 1), making it the closest number.
example_2.py โ€” Tie Case
$ Input: nums = [2, -1, 1]
โ€บ Output: 1
๐Ÿ’ก Note: Both -1 and 1 have the same distance to zero (|โˆ’1| = |1| = 1). Since 1 > -1, we return the positive number 1.
example_3.py โ€” All Negative
$ Input: nums = [-10, -5, -2, -1]
โ€บ Output: -1
๐Ÿ’ก Note: Among all negative numbers, -1 has the smallest absolute distance to zero (|-1| = 1).

Constraints

  • 1 โ‰ค nums.length โ‰ค 1000
  • -105 โ‰ค nums[i] โ‰ค 105
  • The array contains at least one element

Visualization

Tap to expand
0-4distance = 4-2distance = 21distance = 1 (MIN!)4distance = 4Finding Closest Number to ZeroArray: [-4, -2, 1, 4] โ†’ Answer: 1
Understanding the Visualization
1
Position Numbers
Place all numbers on a number line with zero at center
2
Measure Distances
Calculate absolute distance from each number to zero
3
Find Minimum
Identify the number(s) with smallest distance
4
Handle Ties
If multiple numbers have same distance, choose the positive one
Key Takeaway
๐ŸŽฏ Key Insight: Use absolute values to measure distance, but remember to prefer positive numbers in tie situations!
Asked in
Google 15 Amazon 12 Microsoft 8 Apple 6
28.0K Views
Medium Frequency
~8 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen