Largest Number

Solution Code
class Solution:
    def largestNumber(self, nums: list[int]) -> str:
        # Convert each integer to a string
        num_strings = [str(num) for num in nums]
        
        # Sort strings based on concatenated values
        import functools
        def compare(x, y):
            if x + y > y + x:
                return -1
            elif x + y < y + x:
                return 1
            else:
                return 0
                
        num_strings.sort(key=functools.cmp_to_key(compare))
        
        # Handle the case where the largest number is zero
        if num_strings[0] == "0":
            return "0"
            
        # Concatenate sorted strings to form the largest number
        return "".join(num_strings)
Video GuideLeetcode Daily

Time Complexity

O(n log n)

Space Complexity

O(n)