Given an array of integers, return the number closest to 0. If two numbers are equally close, like minus 1 and 1, return the larger one.
DSA Animator › DSA Revision › Arrays › Find Closest Number to Zero
Remember: closest to zero means the smallest absolute value. Always handle the tie rule explicitly: equal distance, keep the larger number. The video solves Find Closest Number to Zero (LeetCode 2239, Easy) with the Basics pattern from the Arrays topic, and you can replay every step in the interactive Find Closest Number to Zero animation.
Given an array of integers, return the number closest to 0. If two numbers are equally close, like minus 1 and 1, return the larger one.
For minus 4, minus 2, 1, 4 and 8, the answer is 1. Its distance from 0 is 1, smaller than every other number.
Sorting by distance would work, but costs O of n log n. One pass that keeps the best answer so far is enough.
Compare distances using the absolute value. Replace the best if a number is strictly closer. If the distance is equal, keep the larger number.
Start with minus 4 as the best. Minus 2 is closer, distance 2, so it becomes the best. 1 is closer still, distance 1, so it becomes the best. 4 and 8 are farther away, so the best stays 1. The answer is 1.
In code, start with the first number as the best. For each number, if its absolute value is smaller, take it. If the absolute values are equal and this number is larger, take it too. One pass, so it's O of n time and O of 1 space.
Remember: closest to zero means the smallest absolute value. Always handle the tie rule explicitly: equal distance, keep the larger number.