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

Difficulty: Easy


Problem Description

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.


Key Insights

  • The problem requires finding the number closest to zero, which involves calculating the absolute values of the numbers.
  • In cases where two numbers are equally close to zero, the larger number should be preferred.
  • The solution can be implemented with a single pass through the array, maintaining a variable to store the closest number found.

Space and Time Complexity

Time Complexity: O(n)
Space Complexity: O(1)


Solution

To solve the problem, we can iterate through the array and keep track of the closest number to zero. We will use a simple comparison to update our closest number based on the absolute value and value itself to ensure we return the larger number in case of ties.

  1. Initialize a variable to hold the closest number (closest) with a value of None or an appropriate initial value.
  2. Traverse each element in the array:
    • Calculate the absolute value of the current number.
    • If closest is None or the absolute value of the current number is less than that of closest, update closest.
    • If the absolute value is the same but the current number is greater than closest, update closest.
  3. Return the closest number once all elements have been considered.

Code Solutions

def findClosestNumber(nums):
    closest = None  # Initialize closest number
    for num in nums:
        # Check if closest is None or if the current number is closer to zero
        if closest is None or abs(num) < abs(closest) or (abs(num) == abs(closest) and num > closest):
            closest = num  # Update closest number
    return closest  # Return the closest number
← Back to All Questions