Practice problem · medium
A payments app runs a bonus draw. Each customer owns several receipt numbers. The customer may write them one after another in any order, with no spaces, to make one long number. The biggest number wins.
You get the receipt numbers of one customer. Find the biggest number they can make.
Write largest_number(pieces).
pieces[i] is a receipt number, a whole number from 0 up."0".Input: pieces = [3, 30, 34, 5, 9]
Output: "9534330"Put piece a before piece b when the text a + b is larger than b + a. Compare the joined texts, not the numbers themselves.
| Pair | a + b | b + a | Order |
|---|---|---|---|
| 3 and 30 | 330 | 303 | 3 first |
| 34 and 3 | 343 | 334 | 34 first |
| 9 and 5 | 95 | 59 | 9 first |
Sorted by that rule the pieces read 9, 5, 34, 3, 30, which joins to 9534330.
Input: pieces = [10, 2]
Output: "210"210 is larger than 102, so 2 goes before 10.
Input: pieces = [0, 0]
Output: "0"Joining gives 00, which is the number 0, written as "0".
1 ≤ pieces.length ≤ 50,0000 ≤ pieces[i] ≤ 1,000,000,000Trying every order means n! orders, and 20 pieces already have more than 2 × 10^18. You need a sort, which costs about n log n comparisons. Each comparison joins two short strings, so it costs a handful of steps.
largest_number · runs in your browserCoding is easiest on a laptop. On a phone, read, trace and try small edits.