DSA AnimatorDSA animations
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.

How to solve Find Closest Number to Zero

LeetCode 2239 · Easy · Arrays · Pattern: Basics

Why the obvious approach is slow

Sorting by distance would work, but costs O(n log n). One pass that keeps the best answer so far is enough.

The key idea

Compare distances using the absolute value. Replace the best if a number is strictly closer. If the distance is equal, keep the larger number.

Remember

Closest to zero means the smallest absolute value. Always handle the tie rule explicitly: equal distance, keep the larger number.

Run the animation above on your own input, or watch the 1:15 video explanation of Find Closest Number to Zero with a dry run and Java code.

More Arrays problems