Largest Number
Arrange integers to form the largest concatenated number — sort by custom comparator (a+b vs b+a).
3 min read
greedy sorting string
Problem#
Given nums, concatenate them in some order to form the largest possible number. Return as string.
Examples#
[10,2]→"210"[3,30,34,5,9]→"9534330"
Constraints#
1 <= n <= 100.
Approach#
Sort strings by a + b > b + a (concatenation comparison). Glue.
Solution#
class Solution {public: string largestNumber(vector<int>& nums) { vector<string> s; s.reserve(nums.size()); 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"; // all zeros string out; for (auto& t : s) out += t; return out; }};import ( "sort" "strconv" "strings")
func largestNumber(nums []int) string { s := make([]string, len(nums)) for i, x := range nums { s[i] = strconv.Itoa(x) } sort.Slice(s, func(i, j int) bool { return s[i]+s[j] > s[j]+s[i] }) if s[0] == "0" { return "0" } return strings.Join(s, "")}from functools import cmp_to_keyfrom typing import List
class Solution: def largestNumber(self, nums: List[int]) -> str: s = [str(x) for x in nums]
def cmp(a: str, b: str) -> int: if a + b > b + a: return -1 if a + b < b + a: return 1 return 0
s.sort(key=cmp_to_key(cmp)) if s[0] == "0": return "0" return "".join(s)function largestNumber(nums) { const s = nums.map(String); s.sort((a, b) => { if (a + b > b + a) return -1; if (a + b < b + a) return 1; return 0; }); if (s[0] === "0") return "0"; return s.join('');}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(); }}function largestNumber(nums: number[]): string { const s = nums.map(String); s.sort((a, b) => { if (a + b > b + a) return -1; if (a + b < b + a) return 1; return 0; }); if (s[0] === "0") return "0"; return s.join('');}Editorial#
The comparator a + b > b + a is the right total order — it works because comparing ab and ba as strings preserves numeric order for the concatenation goal. Transitivity holds because lexicographic comparison of equal-length strings (a+b and b+a have the same length) is consistent.
Complexity#
- Time: O(n log n × L) where L is digit length.
- Space: O(n × L).
Concept revision#
Related#