Largest Number
Medium· custom comparator
Problem
Arrange a list of non-negative integers so that concatenating them forms the largest possible number, and return it as a string. The result should not have leading zeros unless it is exactly "0".
Examples
Input: nums = [3,30,34,5,9]
Output: "9534330"
"3" goes before "30" because "330" > "303".
Input: nums = [0,0]
Output: "0"
Constraints
- • 1 <= nums.length <= 100
- • 0 <= nums[i] <= 10^9
Hints & approach
Hint 1
Sorting numerically, or even as plain strings, does not work. Try [3, 30].
Hint 2
Decide the order of two numbers a and b by comparing a+b with b+a as strings.
Hint 3
Handle the all-zeros case at the end.
Approachtry the hints first
Convert the numbers to strings and sort them with a custom comparator that places a before b when a + b > b + a. This ordering is transitive, so a standard sort yields the arrangement whose concatenation is largest. Join the sorted strings, and if the first character is "0", every value was zero, so return "0".
Time O(n log n * d) for d digits · Space O(n * d)