Leetcode 2239: Find Closest Number to Zero

grid47
grid47
Exploring patterns and algorithms
Mar 28, 2024 4 min read

Given an array of integers, find the number closest to 0. If there are multiple numbers equally close, return the largest number among them.
Problem
Approach
Steps
Complexity
Input: An integer array nums of size n where each element can be negative, positive, or zero.
Example: Input: nums = [-7, 2, 3, -3, 5]
Constraints:
• 1 <= n <= 1000
• -105 <= nums[i] <= 105
Output: Return the integer from the array that is closest to 0. If multiple numbers are equally close, return the largest value.
Example: Output: -3
Constraints:
• The output must be a single integer from the input array.
Goal: Find the number closest to 0 based on its absolute value. If two numbers have the same absolute value, select the larger one.
Steps:
• 1. Iterate through all elements in the array.
• 2. Compare the absolute values of each number to determine the closest to 0.
• 3. If two numbers have the same absolute value, select the one with the larger value.
• 4. Return the resulting number.
Goal: The input array will always have at least one element, and each number is within the specified range.
Steps:
• 1 <= n <= 1000
• -105 <= nums[i] <= 105
Assumptions:
• The input array will never be empty.
• All values in the array are integers.
Input: Input: nums = [-7, 2, 3, -3, 5]
Explanation: The absolute values are [7, 2, 3, 3, 5]. Both 3 and -3 are equally close to 0, but 3 is larger. So, the output is 3.

Input: Input: nums = [4, -4, 1]
Explanation: The absolute values are [4, 4, 1]. Both 4 and -4 are equally close to 0, but 4 is larger. So, the output is 4.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus