Leetcode 2165: Smallest Value of the Rearranged Number

grid47
grid47
Exploring patterns and algorithms
Apr 4, 2024 4 min read

You are given an integer ’num’. Your task is to rearrange the digits of ’num’ such that its value is minimized, with the constraint that the number must not contain any leading zeros. The sign of the number should not change after rearranging the digits.
Problem
Approach
Steps
Complexity
Input: The input consists of a single integer 'num'.
Example: num = 210
Constraints:
• -1015 <= num <= 1015
Output: Return the number formed by rearranging the digits of 'num' to get the smallest possible value without leading zeros and keeping the sign unchanged.
Example: 102
Constraints:
• The rearranged number must not contain leading zeros.
Goal: Rearrange the digits to form the smallest number while respecting the leading zero constraint.
Steps:
• Convert the number to a string and extract the digits.
• Sort the digits in non-decreasing order for positive numbers and non-increasing order for negative numbers.
• Ensure no leading zeros by swapping the first non-zero digit to the front if the number is positive.
Goal: The input number is within the range of -1015 to 1015.
Steps:
• -1015 <= num <= 1015
Assumptions:
• The input number 'num' is always within the specified range.
Input: Example 1: num = 210
Explanation: The digits [2, 1, 0] can be rearranged to form [1, 0, 2]. Since we cannot have leading zeros, the smallest possible value is 102.

Input: Example 2: num = -4306
Explanation: The digits [4, 3, 0, 6] for the negative number can be rearranged to form -6430, which is the smallest value without leading zeros.

Link to LeetCode Lab


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