30. Largest Number
Arrange the non-negative integers in nums so that, written one after another, they form the largest possible number. Return it as a string.
Example 1
Input:
nums = [10,2]Output:
"210"Example 2
Input:
nums = [3,30,34,5,9]Output:
"9534330"Hint 1
Normal numeric sorting fails: 9 must come before 34.
Hint 2
Compare two strings a and b by which concatenation, a+b or b+a, is larger.
Approach 1: Custom comparator sort ✅
Sort strings by the concatenation rule, then join; handle the all-zeros case.
⏱ Time O(n log n · k)💾 Space O(n · k)
Reference solution for Custom comparator sort (time O(n log n · k), space O(n · k)). Each solution passes every test in all four languages.
class Solution:
def largestNumber(self, nums: List[int]) -> str:
s = [str(x) for x in nums]
# a goes before b when a+b is the bigger concatenation
s.sort(key=functools.cmp_to_key(lambda a, b: -1 if a + b > b + a else (1 if a + b < b + a else 0)))
res = ''.join(s)
return '0' if res[0] == '0' else resclass Solution {
public String largestNumber(int[] nums) {
String[] s = new String[nums.length];
for (int i = 0; i < nums.length; i++) s[i] = String.valueOf(nums[i]);
Arrays.sort(s, (a, b) -> (b + a).compareTo(a + b)); // a first when a+b is bigger
if (s[0].equals("0")) return "0";
return String.join("", s);
}
}class Solution {
public:
string largestNumber(vector<int>& nums) {
vector<string> s;
for (int x : nums) s.push_back(to_string(x));
sort(s.begin(), s.end(), [](const string& a, const string& b) { return a + b > b + a; });
if (s[0] == "0") return "0";
string res;
for (auto& x : s) res += x;
return res;
}
};function largestNumber(nums) {
const s = nums.map(String).sort((a, b) => (b + a).localeCompare(a + b)); // a first when a+b is bigger
return s[0] === '0' ? '0' : s.join('');
}Try solving it yourself first. Interviewers care more about how you explain the approach than about the finished code.
This problem is explained in the lesson Sorting Algorithms.
Run your code to see results here.