Largest Number

Arrange integers to form the largest concatenated number — sort by custom comparator (a+b vs b+a).

Medium
Time O(n log n) Space O(n)
LeetCode
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#

Largest Number
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;
}
};

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#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.