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 Zero INPUT 0 -4 -2 1 4 8 nums array: -4 -2 1 4 8 [0] [1] [2] [3] [4] Distance from 0: 4 2 1 4 8 n = 5 elements Goal: Find closest to 0 ALGORITHM STEPS 1 Initialize closest = nums[0] = -4 2 Iterate Array For each num in nums: 3 Compare Distances If |num| < |closest| OR (|num|==|closest| AND num > closest) 4 Update closest closest = num Execution Trace: num=-4: closest=-4 num=-2: |-2|<|-4| --> -2 num=1: |1|<|-2| --> 1 num=4: |4|>|1| --> skip num=8: |8|>|1| --> skip FINAL RESULT Closest number to zero: 1 Output: 1 Distance from 0: |1| = 1 Minimum distance found! Complexity: Time: O(n) - single pass Space: O(1) - constant OK Key Insight: Compare absolute values to find minimum distance. When two numbers have equal distance from zero (e.g., -2 and 2), prefer the positive number. This handles the "largest value" tie-breaker requirement. Single pass achieves O(n) time with O(1) space - optimal for this problem! TutorialsPoint - Find Closest Number to Zero | Single Pass Optimized
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