Largest Number
Medium
Topics
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
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.Input: nums = [10,2] Output: "210" Explanation: "210" beats "102", so 2 goes first even though it is the smaller number.
Example 2
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
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
- Convert every number to its digit string.
- Sort the strings with the comparator:
xbeforeywhenx + yis greater thany + xas strings. Both sides have the same length, so a plain string comparison is the right test. - Concatenate in that order.
- If the result begins with
0then 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 outimport java.util.*;
class Solution {
public String largestNumber(int[] nums) {
String[] parts = new String[nums.length];
for (int i = 0; i < nums.length; i++) parts[i] = String.valueOf(nums[i]);
Arrays.sort(parts, (x, y) -> (y + x).compareTo(x + y));
StringBuilder out = new StringBuilder();
for (String p : parts) out.append(p);
return out.charAt(0) == '0' ? "0" : out.toString();
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: string largestNumber(vector<int>& nums) {
vector<string> parts;
for (int v : nums) parts.push_back(to_string(v));
sort(parts.begin(), parts.end(), [](const string& x, const string& y) {
return x + y > y + x;
})
;
string out;
for (const string& p : parts) out += p;
return out[0] == '0' ? "0" : out;
}
};/**
* @param {number[]} nums
* @return {string}
*/ var largestNumber = function(nums) {
const parts = nums.map(String);
parts.sort((x, y) => {
const xy = x + y, yx = y + x; if (xy > yx) return -1; if (xy < yx) return 1; return 0;
})
;
const out = parts.join("");
return out[0] === "0" ? "0" : out;
};