Largest Number in Python

Finding the largest number from a list of non-negative integers requires arranging them in a specific order. For example, given [10, 2], the largest number would be 210, not 102.

The key insight is to sort numbers based on which arrangement produces a larger concatenated result. We compare two numbers by checking if x + y is greater than y + x as strings.

Algorithm Steps

  • Convert all numbers to strings
  • Sort using a custom comparator that checks concatenated results
  • Join the sorted strings and handle edge cases

Implementation

Let us see the implementation using Python's functools.cmp_to_key ?

from functools import cmp_to_key

class Solution:
    def largestNumber(self, nums):
        # Convert all numbers to strings
        for i in range(len(nums)):
            nums[i] = str(nums[i])
        
        # Sort using custom comparator
        nums.sort(key=cmp_to_key(lambda x, y: self.compare(x, y)))
        
        # Join and handle leading zeros
        result = "".join(nums).lstrip("0")
        return result or "0"
    
    def compare(self, x, y):
        # Compare x+y vs y+x
        if x + y < y + x:
            return 1
        elif x + y == y + x:
            return 0
        else:
            return -1

# Test the solution
solution = Solution()
result = solution.largestNumber([3, 30, 5, 6, 8])
print(result)

The output of the above code is ?

865330

How It Works

The custom comparator checks which concatenation is larger:

  • For numbers 3 and 30: "3" + "30" = "330" vs "30" + "3" = "303"
  • Since "330" > "303", we place 3 before 30
  • This ensures the optimal arrangement for the largest possible number

Alternative Approach Using Lambda

A more concise version using direct lambda comparison ?

from functools import cmp_to_key

def largest_number(nums):
    # Convert to strings and sort with custom key
    str_nums = list(map(str, nums))
    str_nums.sort(key=cmp_to_key(lambda x, y: -1 if x + y > y + x else 1))
    
    # Join and handle edge case
    result = ''.join(str_nums)
    return '0' if result[0] == '0' else result

# Test with different examples
print(largest_number([3, 30, 34, 5, 9]))
print(largest_number([10, 2]))
print(largest_number([0, 0]))

The output of the above code is ?

9534330
210
0

Conclusion

The largest number problem is solved by using a custom comparator that compares concatenated strings. The key insight is that x + y > y + x determines the optimal ordering for maximum value.

Updated on: 2026-03-25T07:49:00+05:30

636 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements