progress

~/problems / Arrays & hashing / Sorting, custom keys, coordinate compression

Largest Number

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

medium ~25 min

Given a list of non-negative integers, arrange them so that writing them one after another forms the largest possible number. Write largest_number(nums) that returns that number as a string (it can be far too long for an int).

  • 1 <= len(nums) <= 10,000; each value is in [0, 10^9].
  • No leading zeros in the answer: if every value is 0, return "0", not "000".

Sorting the values as strings in descending order is not enough: [3, 30] must give "330", not "303". ⭐ Bonus: a speed test with 10,000 values earns a star with O(n log n) comparisons.

largest_number([30, 3, 34, 5, 9])   # "9534330"
largest_number([0, 0])              # "0"
largest_number([121, 12])           # "12121"
largest_number([3, 30])             # "330"
Show hint

you only ever need to decide which of two numbers should come first. Try both orders of the pair and see which gives the bigger string, then sort with that comparison.

Topic: Sorting, custom keys, coordinate compression. sorted(key=...), multi-key and stable sorts, cmp_to_key, compressing coordinates.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc