Facebook Pixel

2239. Find Closest Number to Zero

Problem Description

You are given an integer array nums of size n. Your task is to find the number in the array that has the smallest absolute distance to 0.

The absolute distance of a number x to 0 is simply |x|. For example:

  • The distance of 5 to 0 is |5| = 5
  • The distance of -3 to 0 is |-3| = 3
  • The distance of 0 to 0 is |0| = 0

If there are multiple numbers with the same smallest distance to 0 (like -2 and 2, both having distance 2), you should return the one with the larger value. In this case, you would return 2 since 2 > -2.

The solution uses a single-pass approach where it tracks two variables:

  • ans: the current answer (the number closest to 0)
  • d: the current minimum distance to 0

For each number x in the array, it calculates the absolute value y = |x|. The answer is updated when either:

  1. A smaller distance is found (y < d), or
  2. The same distance is found but the current number is larger (y == d and x > ans)

This ensures that when ties occur, the larger number is chosen as required by the problem.

Quick Interview Experience
Help others by sharing your interview experience
Have you seen this problem before?

Intuition

The key insight is that finding the number closest to 0 is equivalent to finding the number with the smallest absolute value. Since we need to examine every number to determine which one is closest, a single pass through the array is the natural approach.

When thinking about this problem, we realize we need to track two pieces of information as we iterate:

  1. What is the smallest distance we've seen so far?
  2. Which number gave us that distance?

The comparison logic emerges from the problem requirements. For each number, we calculate its distance to 0 using abs(x). We then need to decide: should this number become our new answer?

There are two scenarios where we update our answer:

  • Clear winner: The current number has a smaller distance than anything we've seen before (y < d)
  • Tie-breaker: The current number has the same distance as our current best, but the problem asks for the larger value in case of ties (y == d and x > ans)

For example, if we've already seen -3 (distance = 3) and then encounter 3 (also distance = 3), we should update our answer to 3 because it's larger. Similarly, if we've seen 5 (distance = 5) and then see -2 (distance = 2), we update to -2 because it's closer to 0.

The beauty of this approach is its simplicity - we make our decision for each element immediately based on our current knowledge, without needing to store or sort the entire array. This gives us an optimal O(n) time complexity with O(1) space.

Solution Approach

Following the single-pass approach, we implement the solution by maintaining two variables throughout the traversal:

  1. Initialize tracking variables:

    • ans = 0: Stores the current answer (initially 0)
    • d = inf: Stores the minimum distance seen so far (initially infinity to ensure any distance will be smaller)
  2. Iterate through the array: For each element x in nums:

    • Calculate the absolute distance: y = abs(x)
    • Check if we should update our answer using the condition:
      if (y < d) or (y == d and x > ans):
    • If the condition is met, update both variables:
      ans, d = x, y
  3. Return the result: After examining all elements, ans contains the number closest to 0.

The implementation uses Python's walrus operator (:=) to calculate and assign y = abs(x) inline within the condition check, making the code more concise. The simultaneous assignment ans, d = x, y updates both the answer and the minimum distance in one operation.

Example walkthrough with nums = [2, -1, 1]:

  • Start: ans = 0, d = inf
  • Process 2: y = 2 < inf, update ans = 2, d = 2
  • Process -1: y = 1 < 2, update ans = -1, d = 1
  • Process 1: y = 1 == 1 and 1 > -1, update ans = 1, d = 1
  • Return 1

The algorithm correctly handles edge cases like arrays containing only negative numbers, only positive numbers, or when 0 itself is present in the array. The time complexity is O(n) as we visit each element once, and space complexity is O(1) as we only use two variables regardless of input size.

Ready to land your dream job?

Unlock your dream job with a 5-minute evaluator for a personalized learning plan!

Start Evaluator

Example Walkthrough

Let's walk through the solution with nums = [-4, 2, -1, 3, 1]:

Initial State:

  • ans = 0 (current answer)
  • d = inf (minimum distance seen)

Step 1: Process -4

  • Calculate distance: y = |-4| = 4
  • Check condition: 4 < inf → TRUE
  • Update: ans = -4, d = 4
  • State: The closest number so far is -4 with distance 4

Step 2: Process 2

  • Calculate distance: y = |2| = 2
  • Check condition: 2 < 4 → TRUE
  • Update: ans = 2, d = 2
  • State: Found a closer number! Now 2 is our answer with distance 2

Step 3: Process -1

  • Calculate distance: y = |-1| = 1
  • Check condition: 1 < 2 → TRUE
  • Update: ans = -1, d = 1
  • State: Even closer! -1 has distance 1

Step 4: Process 3

  • Calculate distance: y = |3| = 3
  • Check condition: 3 < 1 → FALSE, 3 == 1 → FALSE
  • No update
  • State: 3 is farther than our current best, keep -1

Step 5: Process 1

  • Calculate distance: y = |1| = 1
  • Check condition: 1 < 1 → FALSE, but 1 == 1 and 1 > -1 → TRUE
  • Update: ans = 1, d = 1
  • State: Same distance as -1, but 1 is larger, so we choose 1

Final Result: 1

The algorithm correctly identifies that both -1 and 1 have the smallest distance (1) to 0, and returns 1 as it's the larger value.

Solution Implementation

1class Solution:
2    def findClosestNumber(self, nums: List[int]) -> int:
3        # Initialize the answer and minimum distance
4        # closest_num will store the number closest to zero
5        # min_distance will store the absolute distance from zero
6        closest_num = 0
7        min_distance = float('inf')
8      
9        # Iterate through each number in the array
10        for num in nums:
11            # Calculate the absolute distance from zero
12            abs_distance = abs(num)
13          
14            # Update the closest number if:
15            # 1. Current number has smaller distance from zero, OR
16            # 2. Current number has same distance but is positive (greater value)
17            if abs_distance < min_distance or (abs_distance == min_distance and num > closest_num):
18                closest_num = num
19                min_distance = abs_distance
20      
21        return closest_num
22
1class Solution {
2    public int findClosestNumber(int[] nums) {
3        // Initialize the result and minimum distance
4        // minDistance is set to a large value (2^30)
5        int closestNumber = 0;
6        int minDistance = 1 << 30;  // Equivalent to 2^30
7      
8        // Iterate through each number in the array
9        for (int currentNumber : nums) {
10            // Calculate the absolute value (distance from zero)
11            int currentDistance = Math.abs(currentNumber);
12          
13            // Update the closest number if:
14            // 1. Current distance is smaller than minimum distance found so far, OR
15            // 2. Current distance equals minimum distance AND current number is positive
16            //    (when distances are equal, prefer the positive number)
17            if (currentDistance < minDistance || 
18                (currentDistance == minDistance && currentNumber > closestNumber)) {
19                closestNumber = currentNumber;
20                minDistance = currentDistance;
21            }
22        }
23      
24        // Return the number closest to zero
25        return closestNumber;
26    }
27}
28
1class Solution {
2public:
3    int findClosestNumber(vector<int>& nums) {
4        // Initialize the result with 0 and minimum distance with a large value (2^30)
5        int closestNumber = 0;
6        int minDistance = 1 << 30;  // 2^30, serves as initial maximum distance
7      
8        // Iterate through each number in the array
9        for (int currentNum : nums) {
10            // Calculate the absolute distance from zero
11            int currentDistance = abs(currentNum);
12          
13            // Update the closest number if:
14            // 1. Current distance is smaller than minimum distance found so far, OR
15            // 2. Current distance equals minimum distance AND current number is positive
16            //    (when distances are equal, prefer the positive number)
17            if (currentDistance < minDistance || 
18                (currentDistance == minDistance && currentNum > closestNumber)) {
19                closestNumber = currentNum;
20                minDistance = currentDistance;
21            }
22        }
23      
24        return closestNumber;
25    }
26};
27
1/**
2 * Finds the number in the array that is closest to zero.
3 * If there are multiple numbers with the same distance to zero, returns the positive one.
4 * @param nums - Array of integers to search through
5 * @returns The number closest to zero
6 */
7function findClosestNumber(nums: number[]): number {
8    // Initialize result and minimum distance
9    // result: the current closest number to zero
10    // minDistance: the absolute distance from zero (initialized to a large value)
11    let result: number = 0;
12    let minDistance: number = 1 << 30; // 2^30, a large initial value
13  
14    // Iterate through each number in the array
15    for (const currentNumber of nums) {
16        // Calculate the absolute distance from zero
17        const distanceFromZero: number = Math.abs(currentNumber);
18      
19        // Update result if we found a closer number to zero
20        // or if the distance is the same but the current number is positive
21        if (distanceFromZero < minDistance || 
22            (distanceFromZero === minDistance && currentNumber > result)) {
23            result = currentNumber;
24            minDistance = distanceFromZero;
25        }
26    }
27  
28    return result;
29}
30

Time and Space Complexity

The time complexity is O(n), where n is the length of the array nums. This is because the algorithm iterates through each element in the array exactly once using a single for loop. Each operation inside the loop (calculating absolute value, comparison operations, and assignments) takes constant time O(1).

The space complexity is O(1). The algorithm only uses a fixed amount of extra space regardless of the input size. It maintains two variables: ans to store the current closest number and d to store the minimum absolute distance found so far. The temporary variable y used in the walrus operator also takes constant space. No additional data structures that grow with input size are used.

Learn more about how to find time and space complexity quickly.

Common Pitfalls

1. Incorrect Initialization of Variables

A common mistake is initializing closest_num with the first element of the array or with float('inf') instead of 0. This can lead to incorrect results when the array doesn't contain the initialized value.

Incorrect:

closest_num = nums[0]  # Wrong! Biases toward first element
min_distance = abs(nums[0])

Correct:

closest_num = 0
min_distance = float('inf')

2. Wrong Comparison for Tie-Breaking

When two numbers have the same distance from zero, forgetting to choose the positive (larger) value is a frequent error. Some might accidentally choose the first occurrence or the smaller value.

Incorrect:

# Missing the tie-breaker condition entirely
if abs_distance < min_distance:
    closest_num = num
    min_distance = abs_distance

# Or using wrong comparison
if abs_distance <= min_distance:  # This always updates on equal distance
    closest_num = num
    min_distance = abs_distance

Correct:

if abs_distance < min_distance or (abs_distance == min_distance and num > closest_num):
    closest_num = num
    min_distance = abs_distance

3. Not Handling the Absolute Value Properly

Forgetting to use absolute value when comparing distances, leading to negative numbers being incorrectly evaluated.

Incorrect:

if num < min_distance:  # Wrong! Compares the actual value, not distance
    closest_num = num
    min_distance = num

Correct:

abs_distance = abs(num)
if abs_distance < min_distance or (abs_distance == min_distance and num > closest_num):
    closest_num = num
    min_distance = abs_distance

4. Edge Case: Array Contains Zero

While the provided solution handles this correctly, some implementations might overlook that when 0 is in the array, it should always be the answer since it has distance 0 from itself.

Solution Verification: The current implementation correctly handles this because when num = 0, abs_distance = 0, which is less than any positive distance, ensuring 0 becomes the answer.

Discover Your Strengths and Weaknesses: Take Our 5-Minute Quiz to Tailor Your Study Plan:

Which data structure is used to implement priority queue?


Recommended Readings

Want a Structured Path to Master System Design Too? Don’t Miss This!

Load More