Python – Arrange given Numbers to form Minimum Number

Arrange given Numbers to form Minimum Number

In this problem, we are given a list of numbers from user via console input. We have to arrange these numbers such that the resulting number is the minimum number possible.

The solution is to sort the given list of numbers in increasing order based on the first digit of these numbers, and then join them.


In the following program, we read a list of numbers from user separated by space. Since the user provides them as a string, we can just split the string into chunks of numbers and sort them as strings lexicographically in ascending order. After that, we join them and print the result. We may also convert this into an integer, if required.

Also, we trim any leading zeros for the numbers after splitting the input string.

Python Program

# Read input
n = input()

# Split input for individual numbers
n_list = n.split(' ')

# Trim any leading zeroes
n_list = [x.lstrip('0') for x in n_list]

# Sort in ascending order lexicographically

# Join the numbers
minimum = ''.join(n_list)

# Convert to integer
minimum = int(minimum)

# Print result

Output #1

52 01 25 6

Output #2

22 6 32 28 96

Output #2

1 4 0 2 3 0058 690

Reference tutorials for the above program


In this Python Tutorial, we learned how to re-arrange given numbers to form the smallest possible number.

Related Tutorials

Code copied to clipboard successfully 👍