We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Find Closest Number to Zero

Number: 2350

Difficulty: Easy

Paid? No

Companies: Google, Amazon, Microsoft, Tiger Analytics


Problem Description

Given an integer array nums, return the number with the value closest to 0. If there are multiple answers (i.e. numbers with the same absolute value), return the number with the largest value.


Key Insights

  • The problem requires comparing numbers based on their absolute values.
  • When two numbers have the same absolute value, the positive number (i.e. the larger number) should be returned.
  • A simple linear pass over the array is sufficient to determine the correct answer.

Space and Time Complexity

Time Complexity: O(n) where n is the number of elements in the array.
Space Complexity: O(1) since only a constant amount of extra space is used.


Solution

The solution involves iterating over the array and maintaining a variable (best) that stores the current number closest to zero. For each number in the array, we compare its absolute value with that of the current best. If the absolute value of the current number is smaller, or it is equal and the number itself is greater (ensuring the positive number is chosen), we update the best variable. Finally, the best number is returned.


Code Solutions

# Function to find the number closest to zero
def findClosestToZero(nums):
    # Initialize best with the first element of the array
    best = nums[0]
    # Iterate over each number in the array
    for num in nums:
        # Check if the current number is closer to zero
        if abs(num) < abs(best) or (abs(num) == abs(best) and num > best):
            best = num
    return best

# Example usage
print(findClosestToZero([-4, -2, 1, 4, 8]))
← Back to All Questions