VOOZH about

URL: https://www.geeksforgeeks.org/dsa/smallest-number-rearranging-digits-given-number/

⇱ Smallest Number by Rearranging Digits - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Smallest Number by Rearranging Digits

Last Updated : 10 Jun, 2026

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.

[Naive Approach] By checking all digit permutations - O(n! × n) Time and O(n) Space

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.


Output
304689

[Better Approach] By sorting the digits - O(n log n) Time and O(n) Space

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.


Output
304689

[Expected Approach] By counting digit frequencies - O(n) Time and O(1) Space

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.


Output
304689



Comment
Article Tags: