Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Build confidence with an intuition-first walkthrough focused on array fundamentals.
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] <= 105Problem summary: 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array
[-4,-2,1,4,8]
[2,-1,1]
find-k-closest-elements)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #2239: Find Closest Number to Zero
class Solution {
public int findClosestNumber(int[] nums) {
int ans = 0, d = 1 << 30;
for (int x : nums) {
int y = Math.abs(x);
if (y < d || (y == d && x > ans)) {
ans = x;
d = y;
}
}
return ans;
}
}
// Accepted solution for LeetCode #2239: Find Closest Number to Zero
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
}
# Accepted solution for LeetCode #2239: Find Closest Number to Zero
class Solution:
def findClosestNumber(self, nums: List[int]) -> int:
ans, d = 0, inf
for x in nums:
if (y := abs(x)) < d or (y == d and x > ans):
ans, d = x, y
return ans
// Accepted solution for LeetCode #2239: Find Closest Number to Zero
/**
* [2239] Find Closest Number to Zero
*
* 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
* -10^5 <= nums[i] <= 10^5
*
*/
pub struct Solution {}
// problem: https://leetcode.com/problems/find-closest-number-to-zero/
// discuss: https://leetcode.com/problems/find-closest-number-to-zero/discuss/?currentPage=1&orderBy=most_votes&query=
// submission codes start here
impl Solution {
pub fn find_closest_number(nums: Vec<i32>) -> i32 {
let mut diff = i32::MAX;
let mut result = 0;
for num in nums {
match diff.cmp(&num.abs()) {
std::cmp::Ordering::Greater => {
diff = num.abs();
result = num;
}
std::cmp::Ordering::Equal if num > result => result = num,
_ => {}
};
}
result
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_2239_example_1() {
let nums = vec![-4, -2, 1, 4, 8];
let result = 1;
assert_eq!(Solution::find_closest_number(nums), result);
}
#[test]
fn test_2239_example_2() {
let nums = vec![2, -1, 1];
let result = 1;
assert_eq!(Solution::find_closest_number(nums), result);
}
}
// Accepted solution for LeetCode #2239: Find Closest Number to Zero
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;
}
Use this to step through a reusable interview workflow for this problem.
Two nested loops check every pair or subarray. The outer loop fixes a starting point, the inner loop extends or searches. For n elements this gives up to n²/2 operations. No extra space, but the quadratic time is prohibitive for large inputs.
Most array problems have an O(n²) brute force (nested loops) and an O(n) optimal (single pass with clever state tracking). The key is identifying what information to maintain as you scan: a running max, a prefix sum, a hash map of seen values, or two pointers.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.