Find Closest Number to Zero Problem
#2239
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 2239.
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
Explanation:
The distance from -4 to 0 is |-4| = 4.
The distance from -2 to 0 is |-2| = 2.
The distance from 1 to 0 is |1| = 1.
The distance from 4 to 0 is |4| = 4.
The distance from 8 to 0 is |8| = 8.
Thus, the closest number to 0 in the array is 1.
Example 2:
Input: nums = [2,-1,1]
Output: 1
Explanation: 1 and -1 are both the closest numbers to 0, so 1 being larger is returned.
Constraints:
1 <= n <= 1000-10^5 <= nums[i] <= 10^5
Solution
Approach: Single Pass
Scan the array and keep the best number so far and its distance d = |x|. A number replaces the best one if its distance is smaller, or if the distance is equal and the number is larger (the positive one wins a tie).
Complexity: O(n) time and O(1) space.
from math import inf
class Solution:
def findClosestNumber(self, nums: List[int]) -> int:
ans, d = 0, inf
for x in nums:
if (y := abs(x)) < d or (y == d and x > ans):
ans, d = x, y
return ans