{x}
blog image

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.

 

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
  • -105 <= nums[i] <= 105

Solution Explanation: Finding the Closest Number to Zero

The problem asks us to find the number in a given integer array that is closest to zero. If multiple numbers have the same minimum distance to zero, we should return the largest among them.

Approach

The most efficient approach is a single-pass linear scan through the array. We keep track of two variables:

  1. ans: Stores the current closest number to zero found so far. Initialized to 0.
  2. d: Stores the minimum distance to zero found so far. Initialized to a large value (e.g., infinity or a very large integer like 1 << 30 to ensure that the first number's distance is smaller).

For each number x in the array, we calculate its absolute value y = |x|. Then we check if y is less than d or if y is equal to d but x is greater than ans. If either of these conditions is true, it means we've found a closer number or a closer number with a larger value, so we update ans and d.

Code Implementation (Python3)

class Solution:
    def findClosestNumber(self, nums: List[int]) -> int:
        ans, d = 0, float('inf') #Initialize d to infinity
        for x in nums:
            y = abs(x)
            if y < d or (y == d and x > ans):
                ans, d = x, y
        return ans

Time and Space Complexity Analysis

  • Time Complexity: O(n), where n is the length of the input array. We iterate through the array once.
  • Space Complexity: O(1). We only use a constant amount of extra space to store the variables ans and d.

Code Implementation in other Languages

The core logic remains the same across different programming languages. Here are examples in Java, C++, Go and TypeScript:

Java

class Solution {
    public int findClosestNumber(int[] nums) {
        int ans = 0, d = Integer.MAX_VALUE; // Initialize d to a large value
        for (int x : nums) {
            int y = Math.abs(x);
            if (y < d || (y == d && x > ans)) {
                ans = x;
                d = y;
            }
        }
        return ans;
    }
}

C++

class Solution {
public:
    int findClosestNumber(vector<int>& nums) {
        int ans = 0, d = INT_MAX; // Initialize d to a large value
        for (int x : nums) {
            int y = abs(x);
            if (y < d || (y == d && x > ans)) {
                ans = x;
                d = y;
            }
        }
        return ans;
    }
};

Go

func findClosestNumber(nums []int) int {
	ans, d := 0, math.MaxInt32 // Initialize d to a large value
	for _, x := range nums {
		y := int(math.Abs(float64(x)))
		if y < d || (y == d && x > ans) {
			ans, d = x, y
		}
	}
	return ans
}
 

TypeScript

function findClosestNumber(nums: number[]): number {
    let ans = 0;
    let d = Infinity; //Initialize d to Infinity
    for (const x of nums) {
        const y = Math.abs(x);
        if (y < d || (y === d && x > ans)) {
            ans = x;
            d = y;
        }
    }
    return ans;
}

All these implementations achieve the same time and space complexity as the Python version. The only difference is in the syntax and how the large initial value for d is represented.