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
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!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code