![]() |
VOOZH | about |
Given a numeric string s, rearrange its digits to form the smallest possible number.
Note: The resulting number must not contain leading zeros.
Examples:
Input: s = "846903"
Output: "304689"
Explanation: 304689 is the smallest number by rearranging the digits.Input: s = "55010"
Output: "10055"
Explanation: 10055 is the smallest number by rearranging the digits.
Table of Content
Generate all possible rearrangements of the digits and discard those with leading zeros. Among all valid permutations, keep track of the smallest number and return it.
304689
Sort all digits in ascending order. If the sorted string starts with zeros, move the smallest non-zero digit to the front and place all zeros immediately after it. This produces the smallest valid number without leading zeros.
304689
Since the input contains only digits 0 to 9, count the frequency of each digit. Place the smallest non-zero digit first, then append the remaining digits in increasing order according to their frequencies. This avoids sorting and constructs the answer in linear time.
304689