Skip to content
Problem 179 · LeetCode 179(opens in a new tab)

Largest Number

MediumGreedy algorithms

You get a list of non-negative whole numbers, nums. Put the numbers side by side in some order and read the digits as one long number.

Choose the order that makes that number as large as possible and return it as a string, since it can be far too long for any integer type. The answer never starts with extra zeros: if every number is 0, return "0".

Example 1

Input:  nums = [4, 42, 45, 8]
Output: "845442"
Why:    8, then 45, then 4, then 42 gives the biggest digits first
2 more examples and the constraints

Example 2

Input:  nums = [0, 0, 0]
Output: "0"
Why:    "000" is just zero, written once

Example 3

Input:  nums = [12, 121]
Output: "12121"
Why:    "12" + "121" = 12121 beats "121" + "12" = 12112

Constraints

  • 1 ≤ length of nums ≤ 100
  • 0 ≤ nums[i] ≤ 1,000,000,000

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Pick the best leaderO(n² · k)
  2. Sort with a glue ruleO(n log n · k)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 100 numbersVerdict
Pick the best leaderO(n² · k)
Passes; selection sort
Sort with a glue ruleO(n log n · k)
Best; one sort, done

n = how many numbers there are, k = digits in the longest one (at most 10).

Edge cases to test

  • All zeros. [0, 0, 0] must give "0", not "000".
  • One number. [7] is just "7".
  • Shared prefix. [12, 121]: comparing digit by digit stalls; gluing both ways shows 12121 > 12112.
  • Trailing zeros. [6, 60, 600] gives "660600": the shortest piece leads.
  • Large values. 1,000,000,000 has ten digits; the answer can be about 1,000 digits, so never parse it as a number.

Common mistakes

  • Sorting by numeric value, which puts 45 ahead of 8.
  • Sorting by plain text order, which puts "42" ahead of "4".
  • Returning "000" for all zeros instead of "0".

How to talk through it

  1. 1Clarify. Can numbers be 0? How long can the result be? Return a string, right?
  2. 2Break the easy sorts. Show [45, 8] against numeric order and [4, 42] against text order.
  3. 3State the rule. a leads b when a + b > b + a. Say it is consistent, so a sort can use it.
  4. 4Code the sort. Convert to strings, sort with the comparator, glue, and fix the all-zeros case.
  5. 5Test out loud. Run [0, 0], [12, 121] and [6, 60, 600] before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?