You are given an integer num. Rearrange the digits of num such that its value is minimized and it does not contain any leading zeros.
Return the rearranged number with minimal value.
Note that the sign of the number does not change after rearranging the digits.
Example 1:
Input: num = 310 Output: 103 Explanation: The possible arrangements for the digits of 310 are 013, 031, 103, 130, 301, 310. The arrangement with the smallest value that does not contain any leading zeros is 103.
Example 2:
Input: num = -7605 Output: -7650 Explanation: Some possible arrangements for the digits of -7605 are -7650, -6705, -5076, -0567. The arrangement with the smallest value that does not contain any leading zeros is -7650.
Constraints:
-1015 <= num <= 1015When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
To solve this problem using the brute force approach, you examine every single possible way to rearrange the digits of the given number. After generating all of these different number combinations, you look through them to find the smallest valid one.
Here's how the algorithm would work step-by-step:
import itertools
def smallest_number(input_number):
number_string = str(input_number)
is_negative_number = number_string.startswith('-')
if is_negative_number:
digit_characters = list(number_string[1:])
all_permutations = list(itertools.permutations(digit_characters))
valid_numeric_values = []
# We generate all digit permutations to evaluate every single possible rearrangement combination
for current_permutation in all_permutations:
reconstructed_value = "".join(current_permutation)
if reconstructed_value[0] == '0':
continue
valid_numeric_values.append(-int(reconstructed_value))
return min(valid_numeric_values)
else:
digit_characters = list(number_string)
all_permutations = list(itertools.permutations(digit_characters))
valid_numeric_values = []
# We generate all digit permutations to evaluate every single possible rearrangement combination
for current_permutation in all_permutations:
reconstructed_value = "".join(current_permutation)
# Leading zeros violate standard integer formatting rules so we must filter them out
if len(reconstructed_value) > 1 and reconstructed_value[0] == '0':
continue
valid_numeric_values.append(int(reconstructed_value))
# Finding the minimum value among valid permutations gives us the optimal rearranged result
return min(valid_numeric_values)To find the smallest possible value after rearranging the digits of a number, we must handle positive and negative numbers differently since signs change how magnitude works. For positive numbers, the goal is to place the smallest non-zero digit at the very front to keep the number as small as possible, followed by the rest of the digits in increasing order. For negative numbers, we want to create the largest possible absolute value by arranging the digits in descending order and then applying the negative sign.
Here's how the algorithm would work step-by-step:
class Solution:
def smallest_number(self, input_number: int) -> int:
if input_number == 0:
return 0
# Positive and negative numbers require opposite sorting strategies to achieve extrema.
if input_number > 0:
digit_characters = sorted(list(str(input_number)))
first_non_zero_index = next(index for index, digit_char in enumerate(digit_characters) if digit_char != '0')
# Moving the first non-zero digit to the front prevents invalid leading zeros.
rearranged_digits = [digit_characters[first_non_zero_index]] + digit_characters[:first_non_zero_index] + digit_characters[first_non_zero_index + 1:]
return int("".join(rearranged_digits))
else:
# Descending order on negative numbers maximizes magnitude, yielding the smallest value.
absolute_digit_chars = sorted(list(str(-input_number)), reverse=True)
return -int("".join(absolute_digit_chars))| Case | How to Handle |
|---|---|
| Single digit numbers | Return the number as is since no rearrangement is possible. |
| Negative numbers | Sort the digits in descending order to form the maximum possible absolute value and preserve the negative sign. |
| Numbers with leading zeros in positive permutation | Find the first non-zero digit, place it at the front, and insert all zeros immediately after it. |
| Zero as an input | Return zero directly without any modification. |
| All identical digits | Return the number as is since sorting yields the exact same value. |
| Integer overflow beyond 64-bit limits during rearrangement | Use string manipulation or standard 64-bit integer types to safely construct and parse the result. |