Largest Number

Medium

Topics
ArrayStringGreedySortingComparator

Given a list of non-negative integers nums, arrange them so that their concatenation forms the largest possible number, and return it as a string.

If every number is zero the answer is "0", not a string of zeros.

Example 1

given102
best order210
answer210
as givenreordered
The numbers are glued together in whatever order makes the result largest, and the chips are shown in that order. It is not descending by value: 2 is placed before the larger 10 because 210 beats 102, so what matters is how a pair reads once joined rather than which number is bigger. The answer comes back as a string because the digits can run longer than an integer holds.
All the numbers are used; none is dropped or repeated.
Input:  nums = [10,2]
Output: "210"
Explanation: "210" beats "102", so 2 goes first even though it is the smaller number.

Example 2

given3303459
best order9534330
answer9534330
as givenreordered
Input:  nums = [3,30,34,5,9]
Output: "9534330"
Explanation: 34 goes before 3 because "343" beats "334", and 3 before 30 because "330" beats "303".

Example 3

given00
best order00
answer0
as givenreordered
Every value here is zero, so no order beats any other and the glued digits would read 00 — which is returned as the single character 0, because a numeric answer has no leading zeros to keep.
Input:  nums = [0,0]
Output: "0"
Explanation: The concatenation is "00", which has to be reported as a single 0.

Constraints

  • 1 <= nums.length <= 100
  • 0 <= nums[i] <= 10^9
Editorial — intuition, approach, complexity and pitfalls

Intuition

Sorting numerically gives the wrong answer and example 1 shows it immediately: 10 is bigger than 2 and belongs second. Sorting by the digit strings is wrong too — that would put "3" before "30" for the right reason and "34" after "3" for the wrong one.

The right comparison is the one the problem is actually asking about: for two numbers x and y, x should come first exactly when x followed by y reads larger than y followed by x. That is a direct test of the thing being optimised, with no reasoning about digit counts or prefixes needed.

What is not obvious is that sorting by this rule is valid — a comparator must be consistent, or the sort is meaningless. It is: the rule is transitive, which is what makes a single sort produce the global optimum rather than just a locally good order.

The all-zeros case is the one special case, because the concatenation is correct and the representation is not.

Approach

  1. Convert every number to its digit string.
  2. Sort the strings with the comparator: x before y when x + y is greater than y + x as strings. Both sides have the same length, so a plain string comparison is the right test.
  3. Concatenate in that order.
  4. If the result begins with 0 then every number was zero — return "0".

Walkthrough

nums = [3, 30, 34, 5, 9]

pairwise tests the comparator makes
   "3"  vs "30"   ->  "330"  >  "303"   so 3 before 30
   "3"  vs "34"   ->  "334"  <  "343"   so 34 before 3
   "5"  vs "9"    ->  "59"   <  "95"    so 9 before 5

sorted: 9, 5, 34, 3, 30
concatenated: "9534330"

Note 34 before 3 before 30 -- neither numeric order (3, 5, 9,
30, 34) nor plain string order (3, 30, 34, 5, 9) produces it.

Complexity

  • Time — O(n log n * d): a comparison sort where each comparison concatenates two strings of at most d digits.
  • Space — O(n * d): the digit strings and the output.

Common Pitfalls

  • Sorting numerically, or by string value. Both are wrong, and on different inputs.
  • Forgetting the all-zeros case. [0, 0] concatenates to "00", which is not a number’s representation.
  • Comparing by length first and then lexicographically. That is an approximation of the right rule and disagrees with it on inputs like [3, 34].
  • Writing the comparator as a subtraction of numbers parsed from the concatenations. With up to 100 numbers of 10 digits those values overflow a fixed-width integer; comparing the strings does not.

Full Solution — all languages

class Solution:
    def largestNumber(self, nums):
        from functools import cmp_to_key
        parts = [str(v) for v in nums]

        def compare(x, y):
            if x + y > y + x:
                return -1
            if x + y < y + x:
                return 1
            return 0

        parts.sort(key=cmp_to_key(compare))
        out = "".join(parts)
        return "0" if out[0] == "0" else out
SensAI
Beta
Tap the mic to stop voice mode