algoadvance

Leetcode 2239. Find Closest Number to Zero

Problem Statement

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

Clarifying Questions

  1. Q: What is the range of values that can be in nums? A: Values can be within the range of standard 32-bit integers, i.e., -2^31 to 2^31 - 1.

  2. Q: What is the size range for the array nums? A: The size of the array nums can vary from 1 to 10^4.

  3. Q: Can the array contain duplicate values? A: Yes, the array can contain duplicate values.

  4. Q: Is the array always non-empty? A: Yes, according to the problem constraints, the array will always contain at least one number.

Strategy

  1. Initialization: Start by initializing a variable to track the closest number to zero. Set it initially to the maximum possible integer value.

  2. Iteration through Array: Iterate through the array, and for each element:
    • Compare its absolute value to the current closest absolute value.
    • If it is closer to zero, update the closest value.
    • If it is equally close but positive, prefer the positive value.
  3. Return Result: At the end of the iteration, return the number stored in the closest value.

Time Complexity

Code

#include <vector>
#include <cstdlib>
#include <climits>

int findClosestNumber(std::vector<int>& nums) {
    int closest = INT_MAX;

    for (int num : nums) {
        if (std::abs(num) < std::abs(closest) || 
           (std::abs(num) == std::abs(closest) && num > closest)) {
            closest = num;
        }
    }

    return closest;
}

Explanation

  1. Initialization:
    int closest = INT_MAX;
    

    This ensures we have a starting comparison point that any number in the array will be closer to zero than.

  2. Iteration:
    for (int num : nums) {
        if (std::abs(num) < std::abs(closest) || 
           (std::abs(num) == std::abs(closest) && num > closest)) {
            closest = num;
        }
    }
    
    • We use std::abs(num) to get the absolute value of the current number.
    • We check if this absolute value is less than the absolute value of the current closest number.
    • If they are equal, we then check if the current number is greater than the closest number (to prefer positives).
  3. Return:
    return closest;
    

    This returns the number in the array that is closest to zero based on the criteria defined.

This approach ensures we efficiently find the desired number using a single pass through the array.

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI