Largest Number (LeetCode 179): Solution and Explanation

Medium
Array
String
Greedy
Sorting

Given a list of non-negative integers, arrange them so that concatenating them in order produces the largest possible number. Return that number as a string, since it can be far too large for any integer type.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

The brute force answer is to try every ordering, concatenate each one, and keep the largest. That is n! orderings, which is hopeless for anything beyond a handful of numbers. Some kind of sort is clearly needed, and the question is what order to sort in.

Sorting numerically in descending order fails right away: for [10, 2] it gives "102", but "210" is larger. Sorting the string forms lexicographically in descending order gets closer, putting "9" before "5" before "34", but it breaks on prefixes. Lexicographically "30" comes after "3", which would put 30 first and produce "303" when "330" is better. The problem is that comparing the two strings alone does not tell you what happens when they are glued together.

So compare exactly what you care about. For two strings a and b, put a first if a + b is larger than b + a. For "3" and "30", "330" beats "303", so "3" goes first. Since a + b and b + a have the same length, a plain string comparison works as a numeric comparison. It can be shown that this rule is transitive, so it is a valid ordering for a sort, and an exchange argument proves the sorted order is optimal: if any adjacent pair were in the wrong order, swapping it would make the result larger. The last detail is that if the largest piece is "0", every piece is zero, and the answer should be "0", not "000".

Approach: Custom comparator sort

  1. Convert every number to a string, giving strs.
  2. Define compare(a, b) that returns -1 when a + b > b + a (so a sorts first), 1 when it is smaller, and 0 when equal.
  3. Sort strs with functools.cmp_to_key(compare).
  4. If the first string after sorting is "0", every number is zero, so return "0".
  5. Otherwise join the strings in sorted order and return the result.

Step-by-step example

nums = [3, 30, 34, 5, 9]
  1. The strings are "3", "30", "34", "5" and "9".
  2. "9" beats every other string because any concatenation starting with 9 is larger, and "5" comes next by the same reasoning.
  3. Comparing "34" and "3": "343" is greater than "334", so "34" goes before "3".
  4. Comparing "3" and "30": "330" is greater than "303", so "3" goes before "30".
  5. The sorted order is "9", "5", "34", "3", "30". The first string is not "0", so the function returns "9534330".

Code: Python, Java, C++

1class Solution:
2    def largestNumber(self, nums: List[int]) -> str:
3        strs = [str(num) for num in nums]
4
5        def compare(a, b):
6            if a + b > b + a:
7                return -1
8            elif a + b < b + a:
9                return 1
10            return 0
11
12        strs.sort(key=functools.cmp_to_key(compare))
13
14        if strs[0] == "0":
15            return "0"
16
17        return "".join(strs)

Time and space complexity

Time

O(n log n × k)

The sort makes O(n log n) comparisons, and each one builds and compares two strings of length up to 2k, where k is the maximum number of digits (at most 10 here).

Space

O(n × k)

The string versions of all numbers and the final joined result each take space proportional to the total number of digits.

Other approaches

Repeat-to-length key (time O(n log n × k), space O(n × k))

Instead of a comparator, sort descending by a key that repeats each string to a fixed length, such as s * 10 truncated, which aligns prefixes so plain string comparison gives the same order. It avoids cmp_to_key and can be faster in Python, but the reasoning is less obvious.

Try all permutations (time O(n! × n × k), space O(n × k))

Generate every ordering and keep the largest concatenation. It is obviously correct and handy for testing the comparator on small inputs, but it is factorial time.

Common mistakes

  • Sorting by plain string order. "30" would come before "3" in descending lexicographic order, producing "303" instead of "330".
  • Returning "000" for input [0, 0, 0]. Check whether the first sorted string is "0" and return "0" in that case.
  • Writing a comparator that returns a boolean in Python. cmp_to_key expects a negative, zero or positive number.
  • Converting the result to an integer. The answer can have hundreds of digits, so it must stay a string.

Frequently asked questions

Why compare a + b with b + a?

It directly asks which of the two possible orders makes a larger concatenation. Since both strings have the same length, a string comparison gives the numeric answer.

Why is the custom comparator a valid sort order?

The relation defined by a + b > b + a is transitive, which can be shown by treating each string as a number scaled by powers of ten. A sort with a transitive comparator produces a consistent order, and swapping any misordered neighbors would only increase the result.

How do you handle all zeros in Largest Number?

After sorting, the largest piece comes first. If it is "0", every piece is zero, so return the single string "0" instead of joining them.