Maximum Concatenation of Nonnegative Integers
Heaps, Sorting & SearchAuto-graded · 27 test casesLast updated
Order a list of nonnegative integers so that joining their decimal forms gives the biggest possible number, using a pairwise concatenation comparator and handling the all-zero case.
Maximum Concatenation
You are given a list values of nonnegative integers. Write each integer in standard decimal form (no leading zeros, except the number 0 itself, which is written as "0"). Reorder the list and join the decimal forms end to end so that the resulting number is as large as possible.
Every element must be used exactly once. Because the result may be far too large for a normal integer type, return it as a string.
Rules
- The result is compared as a number. All candidate arrangements contain the same digits in total, so they have equal length, and comparing them as numbers is the same as comparing them character by character.
- If every element is
0, return the single character string"0", not a string of repeated zeros. - Elements may repeat.
Constraints
1 <= len(values) <= 10^40 <= values[i] <= 10^9- The return value is a string of decimal digits.
Examples
Example 1
Input: max_concatenation([10, 2])
Output: '210'
Example 2
Input: max_concatenation([3, 30, 34, 5, 9])
Output: '9534330'
Example 3
Input: max_concatenation([0, 0])
Output: '0'
Hints
Hint 1
Sorting the numbers by their numeric value, or sorting their string forms alphabetically, both fail. Try [10, 2] and [3, 30] to see why.
Hint 2
Decide the order of any two items x and y by comparing the two strings x+y and y+x. Whichever is larger tells you which item should come first.
Hint 3
Sort the string forms using that pairwise rule, then join them. Afterwards, check whether the result starts with '0'; if so, all inputs were zero.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Whether one number should precede another depends only on how the two combine. For two digit strings x and y, there are just two choices: x + y or y + x. Place x first when x + y is larger.
So we convert every number to a string, sort the strings with this pairwise rule, and join them. If the joined result begins with '0', the largest piece was 0, so every input was zero and we return "0".
Simpler orderings fail:
- Sorting numerically in descending order puts
10before2, giving"102"rather than"210". - Sorting strings alphabetically in descending order puts
"30"before"3", giving"303"rather than"330".
Both strings x + y and y + x have the same length, so comparing them as strings matches comparing them as numbers.
Why it is correct
The rule is consistent. Writing |s| for the digit count of s, the condition x + y > y + x is equivalent to int(x) / (10^|x| - 1) > int(y) / (10^|y| - 1). Each string therefore maps to a real number (the repeating decimal 0.xxx...), and the comparator simply orders by that number. Comparing real numbers is transitive, so the ordering is valid and ties form equivalence classes.
The sorted order is optimal. Suppose an arrangement has an adjacent pair x y where y + x > x + y. Swapping them changes only that block of characters, leaving the prefix and suffix unchanged, and makes the block strictly larger. So the whole number grows. Hence an optimal arrangement has no such adjacent pair, meaning it is sorted under the comparator. Tied elements satisfy x + y == y + x, so swapping them does not change the output.
Edge cases
- All zeros produce a joined string like
"000"; the leading'0'check returns"0". - A single element works directly.
- Shared prefixes such as
3,30,34are handled by the comparator:"343" > "334"and"330" > "303", giving order34, 3, 30. - Values up to
10^9are never converted back to integers, so overflow is not an issue.
Complexity
Let n be the list length and k the maximum digit count (at most 10).
- Time:
O(n log n * k). The sort makesO(n log n)comparisons, each costingO(k). - Space:
O(n k)for the strings and the output.
Reference solution
from functools import cmp_to_key
from typing import List
def max_concatenation(values: List[int]) -> str:
pieces = [str(v) for v in values]
def compare(x: str, y: str) -> int:
# Negative means x should be placed before y.
if x + y > y + x:
return -1
if x + y < y + x:
return 1
return 0
pieces.sort(key=cmp_to_key(compare))
joined = ''.join(pieces)
# A leading zero after sorting means every element was zero.
return '0' if joined and joined[0] == '0' else joined