Largest Number
Problem
Given a list of non-negative integers nums, arrange them so they form the largest possible number and return it as a string.
nums = [3, 30, 34, 5, 9]"9534330"from functools import cmp_to_key
def largest_number(nums):
s = [str(x) for x in nums]
s.sort(key=cmp_to_key(lambda a, b: -1 if a + b > b + a else (1 if a + b < b + a else 0)))
out = "".join(s)
return "0" if out[0] == "0" else out
function largestNumber(nums) {
const s = nums.map(String);
s.sort((a, b) => (b + a).localeCompare(a + b));
const out = s.join("");
return out[0] === "0" ? "0" : out;
}
class 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));
if (s[0].equals("0")) return "0";
StringBuilder sb = new StringBuilder();
for (String t : s) sb.append(t);
return sb.toString();
}
}
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 out;
for (auto& t : s) out += t;
return out;
}
Explanation
To build the largest number, we need to decide the order to glue the numbers together. The clever trick is to compare two numbers as strings: a should come before b whenever a + b (stuck together) is bigger than b + a.
This comparison works because it directly tests "which arrangement of these two reads as a bigger number," and that local choice gives a consistent global order when we sort the whole list with it.
So we turn every number into a string, sort them with that custom rule, then join them all into one big string.
One edge case: if the very first character after sorting is "0", then every number was zero, so the answer is just "0" instead of something like "0000".
Example: [3, 30, 34, 5, 9]. Comparing 3 vs 30: "330" > "303", so 3 goes first. The full sorted order gives "9534330".