← Back to DSA Animator
Find Closest Number to Zero LC #2239 Easy Array Basics · Linear Scan
Problem

Given an integer array nums, return the number with the smallest absolute value. If there is a tie, return the positive number.

Example 1
Input: nums = [-4,-2,1,4,8]
Output: 1
Explanation: |1|=1 is smallest.
Example 2
Input: nums = [2,-1,1]
Output: 1
Explanation: |-1|=|1|=1 (tie) → return positive: 1.
Constraints: 1 ≤ nums.length ≤ 1000  |  −10⁵ ≤ nums[i] ≤ 10⁵
Try Examples
Custom:
Approach
Linear Scan — Track Minimum |value|
Scan left to right. For each element, compare |nums[i]| with the current best. If strictly smaller → update. If equal and nums[i] > 0 → update (positive wins tie). Return the answer.
Array Scan
Variables
Index i
nums[i]
|nums[i]|
answer
Step Logic
Press ▶ Play or Next Step to begin.
🎉
Ready
0 / 0
Select an example above and press Play.
Algorithm
1
Init ans = nums[0]
2
For each nums[i], compute |nums[i]|
3
If |nums[i]| < |ans|: update ans = nums[i]
4
If |nums[i]| == |ans| and nums[i] > 0: ans = nums[i] (tie → positive)
Time
O(n)
Space
O(1)
Why It Works

Distance from zero = absolute value. We keep the element with the smallest |value| seen so far. Tie-breaking: both -x and x have the same distance, but we must return the positive one, so we update when we see a positive tie.