SDE & MLE Prep

179. Largest Number

Problem

Arrange the non-negative integers in nums so that concatenating them forms the largest possible number, and return it as a string (no leading zeros, so all zeros give "0").

Example: [3,30,34,5,9] → "9534330"

Sort strings with the comparator "a before b if a + b > b + a". This ordering is transitive, so the concatenation is maximal. Edge case: all zeros → "0".

Complexity: O(n log n · L).

class Solution:
    def largestNumber(self, nums: List[int]) -> str:
        s = sorted(map(str, nums), key=functools.cmp_to_key(lambda a, b: -1 if a + b > b + a else 1))
        res = "".join(s)
        return "0" if res[0] == "0" else res