DEV Community

Shailesh Kumar
Shailesh Kumar

Posted on

Largest Number | Leetcode Day 25

Given a list of non negative integers, arrange them such that they form the largest number.

Example - """
Input: [10,2]
Output: "210"
"""

Solution -

import functools
class Solution:
    def largestNumber(self, nums: List[int]) -> str:
        def sorted_by(a, b):
            if a+b > b+a:
                return 1
            elif a+b < b+a:
                return -1
            else:
                return 0
        cmp = functools.cmp_to_key(sorted_by)
        return "".join(sorted([str(x) for x in nums], key=cmp, reverse=True)).lstrip('0') or '0'

Top comments (0)