Biggest Number From Cards

MediumsortingAlso known as Largest Number

In a family card game, each player is dealt a few cards with whole numbers printed on them, like 7, 60 and 65. You lay all your cards side by side in a row, and the digits read left to right form one big number. Biggest number wins the round.

Cards cannot be cut or turned over, only reordered. Your cousin keeps putting the card with the biggest value first and keeps losing. Work out the best row.

Your task

Write largestNumber(cards). Return, as a string, the largest number you can form by placing all the cards in some order and joining their digits.

Return the result without extra leading zeros: if every card is 0, return "0", not "000". Return a string because the result can have hundreds of digits.

largestNumber(cards: int[]) → string

Examples

Example 1
Input
cards = [7, 60, 9, 65]
Output
"976560"
Why

Putting the largest card first gives 65 60 9 7 = "656097", which loses. A 9 at the front beats any 6, so 9 goes first, then 7, then 65 before 60. Result "976560".

Example 2
Input
cards = [34, 3, 31]
Output
"34331"
Why

Where does the lone 3 go? Before 34 gives "334…", after it gives "343…", so 34 first. Between 3 and 31: "331" beats "313", so 3 goes before 31. Result "34331".

Constraints

  • 1 ≤ cards.length ≤ 100
  • 0 ≤ cards[i] ≤ 1,000,000,000
Start with brute force

Try every order of the cards, join each one, and keep the biggest. With 10 cards that is 3,628,800 orders; with 20 it is about 2.4 × 10¹⁸. Hopeless.

The quick guesses fail too. Sorting by numeric value puts 10 before 2 and builds "102" instead of "210". Sorting the strings in reverse dictionary order puts "121" before "12" and builds "12112" instead of "12121".

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code