Find Closest Number to Zero - Problem

Given an integer array nums of size n, return the number with the value closest to 0 in nums.

If there are multiple answers, return the number with the largest value.

Input & Output

Example 1 — Basic Case
$ Input: nums = [-4,-2,1,4,8]
Output: 1
💡 Note: The distances are: |-4| = 4, |-2| = 2, |1| = 1, |4| = 4, |8| = 8. The closest to zero is 1.
Example 2 — Tie Breaking
$ Input: nums = [2,-1,1]
Output: 1
💡 Note: Both -1 and 1 have distance 1 from zero. We return 1 since it's the larger value.
Example 3 — Single Element
$ Input: nums = [5]
Output: 5
💡 Note: Only one element, so 5 is the closest to zero.

Constraints

  • 1 ≤ nums.length ≤ 1000
  • -105 ≤ nums[i] ≤ 105

Visualization

Tap to expand
Find Closest Number to ZeroInput:-4-2148Zero Line0Distance = 1(Minimum)Process: Calculate |nums[i] - 0| for each elementOutput: 1
Understanding the Visualization
1
Input
Array of integers with positive and negative values
2
Process
Calculate absolute distance to zero for each number
3
Output
Return number with minimum distance (prefer positive for ties)
Key Takeaway
🎯 Key Insight: Compare absolute distances efficiently while handling tie-breaking in favor of positive values
Asked in
Google 32 Microsoft 28 Amazon 25 Apple 18
28.5K Views
Medium Frequency
~15 min Avg. Time
842 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