DSA AnimatorREVISION VIDEOS
← Back to problems
New

Find Closest Number to Zero — LeetCode 2239 video explanation

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.

Loading videos…

DSA Animator › DSA Revision › Arrays › Find Closest Number to Zero

Key moments in the Find Closest Number to Zero video

0:04Problem0:13Example0:21Brute force0:28Key idea0:37Dry run0:51Code1:05Takeaway

What you will learn

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.

Find Closest Number to Zero video transcript

Problem

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.

Example

For minus 4, minus 2, 1, 4 and 8, the answer is 1. Its distance from 0 is 1, smaller than every other number.

Brute force

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

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.

Dry run

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.

Code

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.

Takeaway

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

More Arrays revision videos

← All 185 DSA revision videos