Python - Largest number possible from list of given numbers

In this article, we will learn how to find the largest possible number from a given list of numbers by arranging them optimally. We'll explore two different approaches to solve this problem effectively.

Method 1: Using itertools.permutations

The first approach generates all possible permutations of the numbers and finds the maximum value ?

import itertools

# initializing the list
numbers = [45, 35, 138, 43, 67]

# result list to store all permutations
result = []

# generate all permutations and join them as strings
for permutation in itertools.permutations(str(number) for number in numbers):
    result.append(''.join(permutation))

# finding the maximum value
maximum = max(result, key=int)

# printing the result
print(int(maximum))
67454335138

Method 2: Using Custom Sorting with functools

A more efficient approach uses a custom comparator to sort numbers based on which concatenation produces a larger result ?

from functools import cmp_to_key

# initializing the list
numbers = [45, 35, 138, 43, 67]

def get_key(first, second):
    if str(first) + str(second) > str(second) + str(first):
        return -1
    return 1

# sorting with custom comparator
result = sorted(numbers, key=cmp_to_key(get_key))

# joining the sorted numbers
result = "".join(str(integer) for integer in result)

# printing the result
print(int(result))
67454335138

How the Custom Comparator Works

The custom comparator compares two numbers by checking which concatenation order produces a larger value. For example, comparing 67 and 45:

# Demonstrating the comparison logic
a, b = 67, 45

# Check which concatenation is larger
concat1 = str(a) + str(b)  # "6745"
concat2 = str(b) + str(a)  # "4567"

print(f"'{concat1}' vs '{concat2}': {concat1 > concat2}")
print(f"So {a} should come before {b}")
'6745' vs '4567': True
So 67 should come before 45

Comparison

Method Time Complexity Space Complexity Best For
Permutations O(n! × n) O(n!) Small lists (< 8 elements)
Custom Sorting O(n log n) O(n) Larger lists (efficient)

Conclusion

The custom sorting approach is more efficient for larger datasets, while permutations work well for small lists. Both methods produce the same correct result by arranging numbers to form the largest possible concatenated value.

Updated on: 2026-03-25T12:21:21+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements