KatInterview

Maximum Concatenation of Nonnegative Integers

Heaps, Sorting & SearchAuto-graded · 27 test cases
MediumAuto-gradedHeaps, Sorting & Searchsortingcustom-comparatorstrings

Last 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^4
  • 0 <= 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.