Find Closest Number to Zero solution and explanation
9 more videos on this problem
Find Closest Number to Zero - Leetcode 2239 - Arrays & Strings (Python)Greg Hogg · 3:24 · 89K views
2239. Find Closest Number to Zero || Leetcode BiWeekly Contest 76 || Leetcode 2239Bro Coders · 4:56 · 5K views
2239. Find Closest Number to Zero (Leetcode Easy)Programming Live with Larry · 2:45 · 2K views
2239. Find Closest Number to Zero | LEETCODE EASY | ARRAYcode Explainer · 3:22 · 2K views
Find Closest Number to Zero - LeetCode 2239 - Javaalgobest - Computer Science · 3:43 · 1K views
2239. Find Closest Number to Zero || solutionViren Variya [IIIT-Delhi] · 8:09 · 1K views
Find Closest Number to Zero - LeetCode 2239 - JavaScott Hacks Code · 4:18 · 1K views
Find Closest Number to Zero | Leetcode 2239 | Amazon Google Facebook interview questionSuper Lazy Coder · 6:06 · 1K views
Find Closest Number to Zero - How to Think and Solve || Leetcode - 2239 || Python Solution || FAANGRelax and Code · 6:26 · 971 views
Leetcode 2239 - Find Closest Number to ZeroShafik Quoraishee · 9:04 · 613 views
The problem
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.
Example 1:
Input: nums = [-4,-2,1,4,8] Output: 1 Explanation: The distance from -4 to 0 is |-4| = 4. The distance from -2 to 0 is |-2| = 2. The distance from 1 to 0 is |1| = 1. The distance from 4 to 0 is |4| = 4. The distance from 8 to 0 is |8| = 8. Thus, the closest number to 0 in the array is 1.
Example 2:
Input: nums = [2,-1,1] Output: 1 Explanation: 1 and -1 are both the closest numbers to 0, so 1 being larger is returned.
Constraints:
1 <= n <= 1000-105 <= nums[i] <= 105
Approach overview
Problem Overview: You receive an integer array and must return the value closest to 0. If two numbers are equally close (for example -3 and 3), return the larger number. The task is essentially scanning the array and tracking the element with the smallest absolute distance from zero.
Approach 1: Iterative Solution with Array Traversal (Time: O(n), Space: O(1))
The most direct approach is a single pass through the array. Maintain a variable that stores the current best candidate. For each element, compute abs(num) and compare it with the absolute value of the current answer. If the new number is closer to zero, update the result. If the absolute values are equal, choose the larger number to satisfy the tie-breaking rule. This method relies only on sequential iteration over the array, performs constant-time comparisons, and requires no additional data structures. Since every element is visited exactly once, the time complexity is O(n) with O(1) extra space.
Approach 2: Recursive Solution (Time: O(n), Space: O(n))
A recursive variant processes one element per function call and passes the current best result forward. Each recursive step compares the current element with the best candidate returned from the remaining subarray. The comparison logic remains identical: evaluate absolute distance from zero and resolve ties by picking the larger number. While the algorithm still examines each element once, recursion introduces call stack overhead proportional to the array length. That results in O(n) time and O(n) auxiliary space due to the recursion stack. This version mainly demonstrates recursion patterns rather than improving performance.
Recommended for interviews: The iterative traversal is the expected answer. Interviewers want to see that you immediately recognize the problem as a linear scan over an array with constant state tracking. Mentioning the tie-breaking condition explicitly and implementing it correctly shows attention to detail. The recursive solution works but adds unnecessary stack overhead, so it’s rarely preferred unless the discussion focuses on recursion techniques.
Approach 1: Approach 1: Iterative Solution with Array Traversal
This approach involves iteratively traversing the array or list to find the solution. It's important to use a loop to iterate through the elements, maintaining variables to track the current state, and update them as needed. This approach is typical for problems such as finding maximums, minimums, or accumulating values.
def example_function(arr):
total = sum(arr)
print(f'Total sum is: {total}')
arr = [1, 2, 3, 4, 5]
example_function(arr)import java.util.Arrays;
public class Example {
public static void exampleFunction(int[] arr) {
int total = Arrays.stream(arr).sum();
System.out.println("Total sum is: " + total);
}
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
exampleFunction(arr);
}
}#include <iostream>
#include <vector>
void exampleFunction(const std::vector<int>& vec) {
int total = 0;
for (int num : vec) {
total += num;
}
std::cout << "Total sum is: " << total << std::endl;
}
int main() {
std::vector<int> vec = {1, 2, 3, 4, 5};
exampleFunction(vec);
return 0;
}function exampleFunction(arr) {
const total = arr.reduce((acc, num) => acc + num, 0);
console.log(`Total sum is: ${total}`);
}
const arr = [1, 2, 3, 4, 5];
exampleFunction(arr);#include <stdio.h>
void exampleFunction(int arr[], int n) {
int total = 0;
for (int i = 0; i < n; i++) {
total += arr[i];
}
printf("Total sum is: %d\n", total);
}
int main() {
int arr[] = {1, 2, 3, 4, 5};
int n = sizeof(arr) / sizeof(arr[0]);
exampleFunction(arr, n);
return 0;
}using System;
using System.Linq;
public class Example {
public static void ExampleFunction(int[] arr) {
int total = arr.Sum();
Console.WriteLine($"Total sum is: {total}");
}
public static void Main() {
int[] arr = {1, 2, 3, 4, 5};
ExampleFunction(arr);
}
}Python simplifies iteration with its built-in sum function to compute the total sum of a list.
Time Complexity: O(n)
Space Complexity: O(1)
Approach 2: Approach 2: Recursive Solution
This approach uses recursion to solve the problem by breaking it down into sub-problems. Recursive solutions can be elegant and succinct but may not always be optimal for large input sizes due to stack overflow risks and lack of tail-call optimization in many languages.
def recursive_sum(arr, n):
if n == 0:
return 0
return arr[n - 1] + recursive_sum(arr, n - 1)
arr = [1, 2, 3, 4, 5]
total = recursive_sum(arr, len(arr))
print(f'Total sum is: {total}')public class Example {
public static int recursiveSum(int[] arr, int n) {
if (n <= 0) return 0;
return arr[n - 1] + recursiveSum(arr, n - 1);
}
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
int total = recursiveSum(arr, arr.length);
System.out.println("Total sum is: " + total);
}
}#include <iostream>
#include <vector>
int recursiveSum(const std::vector<int>& vec, int n) {
if (n == 0) return 0;
return vec[n - 1] + recursiveSum(vec, n - 1);
}
int main() {
std::vector<int> vec = {1, 2, 3, 4, 5};
int total = recursiveSum(vec, vec.size());
std::cout << "Total sum is: " << total << std::endl;
return 0;
}function recursiveSum(arr, n) {
if (n <= 0) return 0;
return arr[n - 1] + recursiveSum(arr, n - 1);
}
const arr = [1, 2, 3, 4, 5];
const total = recursiveSum(arr, arr.length);
console.log(`Total sum is: ${total}`);#include <stdio.h>
int recursiveSum(int arr[], int n) {
if (n <= 0) return 0;
return arr[n - 1] + recursiveSum(arr, n - 1);
}
int main() {
int arr[] = {1, 2, 3, 4, 5};
int n = sizeof(arr) / sizeof(arr[0]);
int total = recursiveSum(arr, n);
printf("Total sum is: %d\n", total);
return 0;
}using System;
public class Example {
public static int RecursiveSum(int[] arr, int n) {
if (n <= 0) return 0;
return arr[n - 1] + RecursiveSum(arr, n - 1);
}
public static void Main() {
int[] arr = {1, 2, 3, 4, 5};
int total = RecursiveSum(arr, arr.Length);
Console.WriteLine($"Total sum is: {total}");
}
}Python solves the problem through recursion by reducing the array's size in each call, mimicking other recursive implementations.
Time Complexity: O(n)
Space Complexity: O(n) (due to call stack)
Approach 3: Single Pass
We define a variable d to record the current minimum distance, initially d=infty. Then we traverse the array, for each element x, we calculate y=|x|. If y \lt d or y=d and x \gt ans, we update the answer ans=x and d=y.
After the traversal, return the answer.
The time complexity is O(n), where n is the length of the array. The space complexity is O(1).
function findClosestNumber(nums: number[]): number {
let [ans, d] = [0, 1 << 30];
for (const x of nums) {
const y = Math.abs(x);
if (y < d || (y == d && x > ans)) {
[ans, d] = [x, y];
}
}
return ans;
}func findClosestNumber(nums []int) int {
ans, d := 0, 1<<30
for _, x := range nums {
if y := abs(x); y < d || (y == d && x > ans) {
ans, d = x, y
}
}
return ans
}
func abs(x int) int {
if x < 0 {
return -x
}
return x
}Complexity comparison
| Approach | Complexity |
|---|---|
| Approach 1: Iterative Solution with Array Traversal | Time Complexity: O(n) |
| Approach 2: Recursive Solution | Time Complexity: O(n) |
| Single Pass | – |
Complexity analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Iterative Array Traversal | O(n) | O(1) | Best general solution. Minimal memory usage and a single pass over the array. |
| Recursive Comparison | O(n) | O(n) | Useful for demonstrating recursion patterns or practicing divide-and-conquer style traversal. |
Frequently asked questions
Is Find Closest Number to Zero easy or hard?
Find Closest Number to Zero is classified as an Easy problem. The challenge focuses on careful comparison logic and handling the tie-breaking rule when two numbers are equally distant from zero.
Find Closest Number to Zero Python/Java solution
In Python or Java, the solution iterates through the array and compares absolute values using Math.abs() or abs(). Update the stored result when a number is closer to zero or when two values tie but the new number is larger. The implementation runs in O(n) time with constant space.
How to solve Find Closest Number to Zero in O(n)?
Iterate through the array once while maintaining a variable storing the closest value found so far. For each number, compare abs(num) with abs(currentBest). Update the result if the new number is closer to zero or if the absolute values are equal but the number is larger. This produces the correct answer in a single O(n) pass.
What is the best approach for Find Closest Number to Zero?
The best approach is a single-pass iterative traversal of the array. Track the current closest value and update it when you find a number with a smaller absolute distance from zero. If two numbers have the same absolute value, choose the larger number. This method runs in O(n) time and uses O(1) extra space.
Is Find Closest Number to Zero asked at Google/Amazon/Meta?
Problems involving array traversal and comparison logic appear frequently in interviews at companies like Amazon, Google, and Meta. While this exact problem may vary slightly, the pattern of scanning an array and tracking a best candidate is a common interview exercise.
What data structure is used in Find Closest Number to Zero?
The problem primarily uses a simple array traversal. No additional data structures such as hash maps, heaps, or trees are required. A single variable is enough to track the current closest number during iteration.
What is the time complexity of Find Closest Number to Zero?
The optimal solution runs in O(n) time because every element in the array must be examined at least once. Each step performs constant-time operations such as absolute value calculation and comparisons. Space complexity is O(1) when implemented iteratively.
