Find Closest Number to Zero

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.

30:00

Find Closest Number to Zero
easy
Free written solution
Topics
Companies

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.

Example 1:
Input: {"nums":[-4,-2,1,4,8]}
Output: 1
Constraints:
  • 1≤n≤10001 \leq n \leq 1000

  • −105≤nums[i]≤105-10^5 \leq \text{nums}[i] \leq 10^5

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"nums":[-4,-2,1,4,8]}

Start with best = nums[0] = -4. Its distance to zero is 4, so anything closer must land strictly inside (-4, 4).

best

-4

|best|

4

x

-

scanned

0/5

distance to zero (scale stretched near 0)

0-88-44best -4

nums

-4
-2
1
4
8
Variables
VariableValue
best-4
dist4
DepthFunction Call
Stack empty
0/9