Sorting Divide-and-conquer sorts

151. Largest Number

Medium

You are given a list of non-negative integers nums. Write all of them one after another, in any order you like, so that together they form the largest possible number. Return that number as a string.

Every number is used exactly once, and its digits stay in their own order. Only the order of the numbers changes.

The answer never starts with a zero unless it is just "0". So when every number is 0, return "0".

Example 1

Input: nums = [7, 71, 709, 8]

Output: "8771709"

Explanation: 8 goes first. Then 7 goes before 71, because 771 is larger than 717, and 71 goes before 709, because 71709 is larger than 70971.

Example 2

Input: nums = [0, 0, 0]

Output: "0"

Explanation: Writing the three zeros together gives 000, and that number is written as 0.

Example 3

Input: nums = [1000000000, 999999999, 0]

Output: "99999999910000000000"

Explanation: The answer has 20 digits, too many for a 64-bit integer. That is why the answer is a string.

Check your understanding

Work out the answer for this input before you write any code.

nums = [4, 40, 45, 8]

Constraints

  • 1 ≤ nums.length ≤ 105
  • 0 ≤ nums[i] ≤ 109

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.