#179

Largest Number

Medium
ArrayStringGreedySortingSortingGreedy
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n!)
O(n log n)
Space
O(n)
O(n)
💡

Intuition

Time O(n log n)Space O(n)

The optimal approach sorts the numbers based on a custom comparison that determines which concatenation of two numbers forms a larger number. This is efficient and avoids the overhead of generating permutations.

⚙️

Algorithm

3 steps
  1. 1Step 1: Convert all integers to strings for comparison.
  2. 2Step 2: Sort the strings based on a custom comparator that checks which concatenation is larger.
  3. 3Step 3: Concatenate the sorted strings to form the largest number.
solution.py9 lines
1from functools import cmp_to_key
2
3def compare(x, y):
4    return (y + x > x + y) - (y + x < x + y)
5
6def largestNumber(nums):
7    nums_str = list(map(str, nums))
8    nums_str.sort(key=cmp_to_key(compare))
9    return ''.join(nums_str) if nums_str[0] != '0' else '0'

Complexity note: The time complexity is O(n log n) due to the sorting step, which is efficient for the input size. The space complexity is O(n) for storing the string representations of the numbers.

  • 1The order of concatenation matters significantly in determining the largest number.
  • 2Sorting with a custom comparator is key to solving this problem efficiently.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.