algoadvance

Given an integer array nums of size n, find the number that is closest to zero. If there are multiple answers, return the number with the largest value.

Clarifying Questions

  1. Input Range: What are the minimum and maximum possible sizes for the array nums?
  2. Value Range: What are the minimum and maximum possible values for elements in nums?
  3. Edge Cases: Can the array contain duplicate values? Can the array be empty?
  4. Output: Should the function return an integer? What should it return if the array is empty?

Code

Let’s write the code, keeping in mind to handle edge cases as well.

def findClosestNumber(nums):
    # Handle the case where nums is empty
    if not nums:
        return None  # Assuming returning None for an empty list

    # Initialize the closest number to a very large value
    closest_num = float('inf')
    
    for num in nums:
        # Check if this number is closer to zero than the closest_num found so far
        if abs(num) < abs(closest_num):
            closest_num = num
        # If it ties for closeness, choose the larger value
        elif abs(num) == abs(closest_num):
            closest_num = max(closest_num, num)
    
    return closest_num

Strategy

  1. Initialization: Start with closest_num set to positive infinity.
  2. Iterate through the Array: For each number in nums, check the following:
    • If the absolute value of the current number is less than the absolute value of closest_num, update closest_num.
    • If the absolute values are equal, update closest_num to be the maximum of the current number and closest_num.
  3. Return Result: After iterating through the array, return the closest_num.

Time Complexity

Try our interview co-pilot at AlgoAdvance.com