LeetCode 2239. Find Closest Number to Zero (Easy)

LeetCode 2239. Find Closest Number to Zero (Easy)

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.

Input 1 : nums = [-4,-2,1,4,8]
Output: 1

Input 2: nums = [2,-1,1]
Output: 1

Think with me:

  • The task is to find the element in the array that is close to 0.
  • Let's start by assuming that the first element in the array 'nums[0]' is the closest to 0. Let's call this cn (short for closest number)
  • Then, we will iterate through the entire array and check if there is a number that is smaller than the cn. But, we also need to take note that there can be negative numbers in the array as well. So, we compare the positive one's only.
  • So, we will check if the absolute value of ith element in the array is less than the absolute value of cn. If there is, then we will set the value of cn equal to that i
  • This loop will go on till we have fully iterated through the array.
  • Next, we will check if the cn that we got from the previous step is less than zero or negative (because we actually compared the absolute/positive value) and also check if the absolute/positive of the cn exists in the given array nums
  • If both the conditions are true, then we will set the cn equal to the absolute/positive of the current cn. This is because, in the problem statement we are told: if there are multiple values,. return the number with the largest value.

Python Code

Here is the python code for the problem:

def findClosestNumber(nums):
    cn = nums[0]
    
    for i in nums:
        if abs(i) < abs(cn):
            cn = i
        if cn < 0 and abs(cn) in nums:
            cn = abs(cn)
    return cn
LeetCode Link

Practical Tips

  • Take a pen and paper
  • Walk through the code by writing it
  • Literally, write each iteration of the array and see how the cn is updated
  • Don't worry if you were not able to solve this question at all, it happens to someone. We all start somewhere. Cheer up!

Conclusion

Write the code and each iteration on a paper. Revise it the next day.

Even if you are not able to solve anything, just do it everyday. Use pen and paper everyday. A day will come when you finally have that algorithmic satisfaction!

← Back to Blog