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
[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.
#include <bits/stdc++.h>
using namespace std;
// Return the smallest number possible by rearranging the digits.
string minimumNumber(string &s) {
string res = "";
sort(s.begin(), s.end());
do {
if (s[0] != '0') {
res = s;
break;
}
} while (next_permutation(s.begin(), s.end()));
return res;
}
int main() {
string s = "846903";
cout << minimumNumber(s);
return 0;
}
import java.util.Arrays;
public class GFG {
// Return the smallest number possible by rearranging the digits.
static String minimumNumber(String s) {
char[] arr = s.toCharArray();
Arrays.sort(arr);
do {
if (arr[0] != '0') {
return new String(arr);
}
} while (nextPermutation(arr));
return "";
}
static boolean nextPermutation(char[] arr) {
int i = arr.length - 2;
while (i >= 0 && arr[i] >= arr[i + 1]) {
i--;
}
if (i < 0) {
return false;
}
int j = arr.length - 1;
while (arr[j] <= arr[i]) {
j--;
}
char temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
int left = i + 1;
int right = arr.length - 1;
while (left < right) {
temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
left++;
right--;
}
return true;
}
public static void main(String[] args) {
String s = "846903";
System.out.println(minimumNumber(s));
}
}
from itertools import permutations
# Return the smallest number possible by rearranging the digits.
def minimum_number(s):
res = None
for p in permutations(s):
# Ignore numbers with leading zero.
if p[0] == '0':
continue
curr = "".join(p)
if res is None or curr < res:
res = curr
return res
if __name__ == "__main__":
s = "846903"
print(minimum_number(s))
using System;
using System.Collections.Generic;
class GFG
{
// Return the smallest number possible by rearranging the digits.
static string MinimumNumber(string s)
{
string res = null;
foreach (var p in GetPermutations(s.ToCharArray(), 0))
{
string curr = new string(p);
// Ignore numbers with leading zero.
if (curr[0] == '0')
{
continue;
}
if (res == null || string.Compare(curr, res) < 0)
{
res = curr;
}
}
return res;
}
static IEnumerable<char[]> GetPermutations(char[] arr, int index)
{
if (index == arr.Length)
{
yield return (char[])arr.Clone();
yield break;
}
for (int i = index; i < arr.Length; i++)
{
(arr[index], arr[i]) = (arr[i], arr[index]);
foreach (var p in GetPermutations(arr, index + 1))
{
yield return p;
}
(arr[index], arr[i]) = (arr[i], arr[index]);
}
}
static void Main()
{
string s = "846903";
Console.WriteLine(MinimumNumber(s));
}
}
// Return the smallest number possible by rearranging the digits.
function minimumNumber(s) {
let res = null;
function generate(arr, index) {
if (index === arr.length) {
const curr = arr.join("");
// Ignore numbers with leading zero.
if (curr[0] !== '0') {
if (res === null || curr < res) {
res = curr;
}
}
return;
}
for (let i = index; i < arr.length; i++) {
[arr[index], arr[i]] = [arr[i], arr[index]];
generate(arr, index + 1);
[arr[index], arr[i]] = [arr[i], arr[index]];
}
}
generate(s.split(""), 0);
return res;
}
const s = "846903";
console.log(minimumNumber(s));
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.
#include <bits/stdc++.h>
using namespace std;
// Return the smallest number possible by rearranging the digits.
string minimumNumber(string &s) {
sort(s.begin(), s.end());
int i = 0;
while (i < s.size() && s[i] == '0') {
i++;
}
if (i < s.size()) {
swap(s[0], s[i]);
}
return s;
}
int main() {
string s = "846903";
cout << minimumNumber(s);
return 0;
}
import java.util.Arrays;
public class GFG {
// Return the smallest number possible by rearranging the digits.
static String minimumNumber(String s) {
char[] arr = s.toCharArray();
Arrays.sort(arr);
int i = 0;
while (i < arr.length && arr[i] == '0') {
i++;
}
if (i < arr.length) {
char temp = arr[0];
arr[0] = arr[i];
arr[i] = temp;
}
return new String(arr);
}
public static void main(String[] args) {
String s = "846903";
System.out.println(minimumNumber(s));
}
}
# Return the smallest number possible by rearranging the digits.
def minimum_number(s):
arr = sorted(s)
i = 0
while i < len(arr) and arr[i] == '0':
i += 1
if i < len(arr):
arr[0], arr[i] = arr[i], arr[0]
return "".join(arr)
if __name__ == "__main__":
s = "846903"
print(minimum_number(s))
using System;
class GFG
{
// Return the smallest number possible by rearranging the digits.
static string MinimumNumber(string s)
{
char[] arr = s.ToCharArray();
Array.Sort(arr);
int i = 0;
while (i < arr.Length && arr[i] == '0')
{
i++;
}
if (i < arr.Length)
{
char temp = arr[0];
arr[0] = arr[i];
arr[i] = temp;
}
return new string(arr);
}
static void Main()
{
string s = "846903";
Console.WriteLine(MinimumNumber(s));
}
}
// Return the smallest number possible by rearranging the digits.
function minimumNumber(s) {
const arr = s.split("").sort();
let i = 0;
while (i < arr.length && arr[i] === '0') {
i++;
}
if (i < arr.length) {
[arr[0], arr[i]] = [arr[i], arr[0]];
}
return arr.join("");
}
// Driver Code
const s = "846903";
console.log(minimumNumber(s));
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.
#include <bits/stdc++.h>
using namespace std;
// Return the smallest number possible by rearranging the digits.
string minimumNumber(string &s) {
vector<int> freq(10, 0);
for (char ch : s) {
freq[ch - '0']++;
}
string res = "";
// Place the smallest non-zero digit first.
for (int d = 1; d <= 9; d++) {
if (freq[d] > 0) {
res += char('0' + d);
freq[d]--;
break;
}
}
// Append the remaining digits.
for (int d = 0; d <= 9; d++) {
res.append(freq[d], char('0' + d));
}
return res;
}
int main() {
string s = "846903";
cout << minimumNumber(s);
return 0;
}
public class GFG {
// Return the smallest number possible by rearranging the digits.
static String minimumNumber(String s) {
int[] freq = new int[10];
for (char ch : s.toCharArray()) {
freq[ch - '0']++;
}
StringBuilder res = new StringBuilder();
// Place the smallest non-zero digit first.
for (int d = 1; d <= 9; d++) {
if (freq[d] > 0) {
res.append((char)('0' + d));
freq[d]--;
break;
}
}
// Append the remaining digits.
for (int d = 0; d <= 9; d++) {
while (freq[d]-- > 0) {
res.append((char)('0' + d));
}
}
return res.toString();
}
public static void main(String[] args) {
String s = "846903";
System.out.println(minimumNumber(s));
}
}
# Return the smallest number possible by rearranging the digits.
def minimum_number(s):
freq = [0] * 10
for ch in s:
freq[int(ch)] += 1
res = []
# Place the smallest non-zero digit first.
for d in range(1, 10):
if freq[d] > 0:
res.append(str(d))
freq[d] -= 1
break
# Append the remaining digits.
for d in range(10):
res.extend(str(d) for _ in range(freq[d]))
return "".join(res)
if __name__ == "__main__":
s = "846903"
print(minimum_number(s))
using System;
class GFG
{
// Return the smallest number possible by rearranging the digits.
static string MinimumNumber(string s)
{
int[] freq = new int[10];
foreach (char ch in s)
{
freq[ch - '0']++;
}
string res = "";
// Place the smallest non-zero digit first.
for (int d = 1; d <= 9; d++)
{
if (freq[d] > 0)
{
res += (char)('0' + d);
freq[d]--;
break;
}
}
// Append the remaining digits.
for (int d = 0; d <= 9; d++)
{
while (freq[d]-- > 0)
{
res += (char)('0' + d);
}
}
return res;
}
static void Main()
{
string s = "846903";
Console.WriteLine(MinimumNumber(s));
}
}
// Return the smallest number possible by rearranging the digits.
function minimumNumber(s) {
const freq = new Array(10).fill(0);
for (const ch of s) {
freq[ch.charCodeAt(0) - 48]++;
}
let res = "";
// Place the smallest non-zero digit first.
for (let d = 1; d <= 9; d++) {
if (freq[d] > 0) {
res += d;
freq[d]--;
break;
}
}
// Append the remaining digits.
for (let d = 0; d <= 9; d++) {
while (freq[d]-- > 0) {
res += d;
}
}
return res;
}
// Driver Code
const s = "846903";
console.log(minimumNumber(s));
Output
304689