Smallest Value of the Rearranged Number — LeetCode 2165 Python Solution

MediumMathSorting
Problem
#2165
Pattern
Sorting
Reading time
5 min

The problem

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.

Example

Input
num = 310
Output
103
Explanation
The possible arrangements for the digits of 310 are 013, 031, 103, 130, 301, 310.

Python solution

Python
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

Complexity

MeasureComplexity
TimeO(\log n), where n is the size of the number \textit{num}
SpaceO(1) auxiliary

Pattern: Sorting

Spend O(n log n) once to buy an ordering that makes the rest of the problem trivial. LeetCode 2165. Smallest Value of the Rearranged Number is filed here because LeetCode tags it Sorting, which is the vocabulary this hub collects.

The sorting guide has the Python template for the pattern and the 401 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2165. Smallest Value of the Rearranged Number?
LeetCode 2165. Smallest Value of the Rearranged Number is rated Medium on LeetCode.
What is the time complexity of LeetCode 2165. Smallest Value of the Rearranged Number?
The Python solution on this page runs in O(\log n), where n is the size of the number \textit{num}.
What is the space complexity of LeetCode 2165. Smallest Value of the Rearranged Number?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 2165. Smallest Value of the Rearranged Number cover?
LeetCode 2165. Smallest Value of the Rearranged Number is tagged Math and Sorting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview