The largest number
- O(n log n) · Hard
- Full plan
- Python
- JavaScript
- lists
- sorting
- digits
Problem
You get a list of loose digits, each one from 0 to 9, and you have to arrange them to build the largest number you can.
With 4, 5, 6 and 1 the answer is 6541: the biggest digit rules, because whatever sits up front is worth more than everything else together.
The rules: every digit is used and none is left out, so if the 4 shows up three times, it shows up three times in the answer. If the list comes in empty, you return 0.
The way in is sorting: put the digits from largest to smallest and stick them together in that order. To stick them together you can start at 0 and, with each digit, multiply what you have by 10 and add the digit.
Watch that last part: you have to return a number, not a string.
Examples
Three digits
[1, 2, 3] → 321
Four out of order
[4, 5, 6, 1] → 6541
With a nine
[1, 2, 3, 9] → 9321
A repeated digit
[4, 4, 1, 4] → 4441
Besides these, the challenge has hidden tests that are revealed when you submit your solution.
You start with this
Python
def largest_number(digits):
passJavaScript
function largestNumber(digits) {
}It opens in your browser, with the editor and the tests. This challenge is part of the full plan; the O(1) and O(log n) ones are free.