Day 1: Find Closest Number to Zero – My Leetcode Journey

Brad Malgas
Author
Solved Leetcode 2239 by writing the algorithm out on paper first. Ended up with an O(N) solution optimized down to 3ms runtime.
The first problem on my Leetcode journey was 2239. Find Closest Number to Zero. In an effort to track progress, I decided to time myself.
The solution itself was fairly simple—I focused on following my 5 problem-solving steps: Write down → Solve → Code solution → Analyze → Optimize.
My approach was straightforward. Upon reading the problem, I immediately thought of two things:
- I can use the absolute value to check the distance between the number and zero, i.e., find the one that is closest to zero.
- The problem stated that if there are multiple answers, I need to return the largest. That means if I have a negative and a positive of the same number, I return the positive one.
Before even touching the code, I wrote down and tested the algorithm on paper. The steps were as follows:
-
Set the first item in the array to a variable called
smallest. -
Loop through the remainder of the array indexes (i.e., index 1 until index length of array - 1).
-
For each index, check the following:
- If the absolute value of the number at the current index is smaller than the absolute value of our current
smallest, then updatesmallestto the number at the current index. - If the absolute value of the number at the current index is equal to the absolute value of
smallest(meaning we are working with the positive and negative version of the same number), then updatesmallestto the positive version.
- If the absolute value of the number at the current index is smaller than the absolute value of our current
The first if statement finds the closest number to zero, and the second handles the case where we have both positive and negative versions of the same number (e.g., 1 and -1). This solution has a time complexity of O(N) and a space complexity of O(1).
I managed to solve the problem in 14 minutes and 2 seconds. However, my first solution had a runtime of 6ms and used 18MB of memory. My only optimization was using variables to store common array lookups. After optimizing, I reduced this to 3ms runtime with 17.9MB of memory.
To see where I could improve, I looked at some of the top submissions on Leetcode as well as the AlgoMap video.
My solution can be found on my GitHub: 2239. Find Closest Number to Zero.py
Loading reactions…
Loading comments…