algoadvance

Leetcode 2239. Find Closest Number to Zero

Problem Statement

Given an integer array nums of size n, find the number that is closest to zero. If there are multiple answers, return the number with the largest value.

Clarifying Questions

  1. Q: What are the constraints on the size of the array n? A: The size of the array n can be between 1 and 10^3.

  2. Q: Can the array nums contain both positive and negative integers? A: Yes, the array can contain both positive and negative integers, as well as zero.

  3. Q: What should be the output if the closest numbers to zero are both positive and negative with the same distance from zero? A: Return the positive number.

  4. Q: Do we need to handle any special input cases, such as empty arrays or arrays of a single element? A: Since the problem guarantees at least one element (size n ≥ 1), we don’t need to worry about empty arrays but should handle single-element arrays.

Strategy

  1. Initialize a variable to keep track of the closest number found so far. This will be updated as we iterate over each element in the array.
  2. Iterate through each number in the array:
    • Calculate the absolute value of the current number.
    • Compare with the absolute value of the closest number found so far.
    • Update the closest number if the current number is closer to zero, or if they are equally close but the current number is larger.
  3. Return the final closest number.

Code

public class Solution {

    public int findClosestNumber(int[] nums) {
        // Initialize the closest number to a large positive value
        int closest = Integer.MAX_VALUE;

        for (int num : nums) {
            // If current number is closer to zero or is equally close but positive and larger in value, update closest
            if (Math.abs(num) < Math.abs(closest) || (Math.abs(num) == Math.abs(closest) && num > closest)) {
                closest = num;
            }
        }

        return closest;
    }

    public static void main(String[] args) {
        Solution sol = new Solution();
        int[] nums1 = {-4, -2, 1, 4, 8};
        int[] nums2 = {2, -1, 1};
        System.out.println(sol.findClosestNumber(nums1)); // Output: 1
        System.out.println(sol.findClosestNumber(nums2)); // Output: 1
    }
}

Time Complexity

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI