Smallest Value of the Rearranged Number Problem
#2165
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 2165.
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:
-10^15 <= num <= 10^15
Solution
Approach: Counting digits
Count how many times each digit occurs in |num|.
If num is negative, the smallest value is the one with the largest magnitude, so write the digits from 9 down to 0.
If num is positive, put the smallest non-zero digit first, so there is no leading zero, then write the remaining digits in ascending order.
Complexity: time O(log |num|), space O(1).
class Solution:
def smallestNumber(self, num: int) -> int:
neg = num < 0
num = abs(num)
cnt = [0] * 10
while num:
cnt[num % 10] += 1
num //= 10
ans = 0
if neg:
for i in reversed(range(10)):
for _ in range(cnt[i]):
ans *= 10
ans += i
return -ans
if cnt[0]:
for i in range(1, 10):
if cnt[i]:
ans = i
cnt[i] -= 1
break
for i in range(10):
for _ in range(cnt[i]):
ans *= 10
ans += i
return ans