Biggest Number From Cards

MediumsortingAlso known as Largest Number

In a family card game, each player gets a few cards printed with whole numbers, like 7, 60 and 65. You lay your cards in a row, and the digits read left to right form one big number. The player with the biggest number wins.

Cards can be reordered but not cut or flipped. Your cousin always leads with the highest card and keeps losing, so you want to find the row that really gives the biggest number.

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 it 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

Largest card first gives 65 60 9 7 = "656097", which loses. A leading 9 beats any 6, so 9 goes first, then 7, then 65 before 60: "976560".

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

Before 34, the 3 gives "334…"; after it, "343…", so 34 goes 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 and keep the biggest join. With 10 cards that is 3,628,800 orders; with 20, about 2.4 × 10¹⁸. Hopeless.

The quick guesses fail too. Sorting by numeric value puts 10 before 2 and builds "102" instead of "210". 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