You are given an array of nonnegative integers nums. Write each integer in decimal, then place all of these pieces side by side in some order so that the resulting concatenation is as large as possible. Every element must be used exactly once.
Return the result as a string, since it may be far too large to fit in any numeric type.
If every element of nums is zero, the answer is the single character "0", with no repeated zeros.
Function Signature
def largest_number(nums: list[int]) -> str:
Rules
-
Each integer is written in its ordinary decimal form with no leading zeros, so
0
is written as
"0"
.
-
The returned string has no leading zeros unless the whole answer is
"0"
.
Constraints
-
1 <= len(nums) <= 100
-
0 <= nums[i] <= 10^9
Examples
Input: nums = [50, 2, 1, 9]
Output: "95021"
"9" goes first because "9" followed by any other piece beats the reverse order. Next, "50" goes before "2" because "502" > "250", and "2" goes before "1" because "21" > "12".
Input: nums = [121, 12]
Output: "12121"
"12" + "121" = "12121" is larger than "121" + "12" = "12112", so "12" goes first even though "121" is larger in plain string order.
Input: nums = [0, 0]
Output: "0"
Joining the pieces gives "00", and an all-zero input is returned as the single character "0".