DSA Factory
Free Sorting lessonsSorting · Stage 3 · Mastery · Step 1

Arrange for the biggest number

Glue numbers together in the order that makes the biggest result, by inventing your own rule for which comes first. About 14 minutes.

A rule between two items

Given 3, 30 and 34, which order makes the biggest number when glued together? Putting the biggest number first gives 34, 30, 3, which makes 34303. But the order 34, 3, 30 makes 34330, which is bigger.

Sorting by the numbers themselves doesn't work. Instead decide for each pair which should come first: put a before b if gluing a then b gives a bigger result than b then a. If the rule is consistent, sorting with it gives the best arrangement.

Pair rule: a goes before b if a then b is bigger.
Compare as text: glued numbers can be too big for a number type.
In code
a, b = "3", "30"
first = a + b     # "330"
second = b + a    # "303"
Order 8, 89, 9 to make the biggest number.
8
0
89
1
9
2
leftright

Try the pair 8 and 89: 889 versus 898. 898 is bigger, so 89 goes before 8.

Move 1 of 3
Quick check

Should 9 come before 91 when making the biggest number?

  1. AYes, because 991 is bigger than 919
  2. BNo, because 91 is the bigger number
  3. CIt makes no difference
Show the answer

Yes, because 991 is bigger than 919. Compare the glued results: 9 then 91 is 991, and 91 then 9 is 919.

Your problem

Biggest number from the pieces

nums is a list of non-negative whole numbers. Arrange them in some order and glue their digits together to make the biggest possible number. Return that number as a string, because it may be very long. If the list is all zeros, return "0".

Example
nums = [3, 30, 34, 5, 9] → "9534330"

1 ≤ length ≤ 300 · 0 ≤ value ≤ 1,000,000,000

Solve it in your browserFree account, no card. Python, C++, Java or JavaScript, with hints if you get stuck, and your progress is saved.
Sign up free to solve