#2239

Find Closest Number to Zero

Easy
ArrayArrayTwo Pointers
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal solution is similar to the brute force approach but focuses on maintaining the closest number more efficiently in a single pass through the array.

⚙️

Algorithm

5 steps
  1. 1Step 1: Initialize a variable to keep track of the closest number to zero.
  2. 2Step 2: Loop through each number in the array.
  3. 3Step 3: For each number, check if its absolute value is less than the current closest number's absolute value.
  4. 4Step 4: If they are equal, choose the larger number.
  5. 5Step 5: Update the closest number if necessary and return it after the loop.
solution.py11 lines
1# Full working Python code
2
3def findClosestNumber(nums):
4    closest = nums[0]
5    for num in nums:
6        if abs(num) < abs(closest) or (abs(num) == abs(closest) and num > closest):
7            closest = num
8    return closest
9
10# Example usage
11print(findClosestNumber([-4,-2,1,4,8]))  # Output: 1

Complexity note: The time complexity remains O(n) as we still traverse the array once, and the space complexity is O(1) since we only use a constant amount of extra space.

  • 1The absolute value is crucial when determining proximity to zero.
  • 2When two numbers are equally close to zero, the larger number should be preferred.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.