Largest Number

Put a list of numbers in the order that, written side by side, makes the largest number.

You are given an array nums of non-negative integers. Arrange them so that, written one after another, they form the largest possible number. Return that number as a string, since it can be far too big for any Java integer type.

Example 1
Input: nums = [10, 2]
Output: "210"
Example 2
Input: nums = [3, 30, 34, 5, 9]
Output: "9534330"
Solution

The Idea

Picture five number cards on a table: 3, 30, 34, 5 and 9. You lay all of them in a row, and the digits, read from left to right, form one long number. Which order makes that number as large as possible?

As in any number, the first digit counts the most. So the card that starts with the biggest digit goes first: 9, then 5. That leaves 3, 30 and 34, which all start with 3, so the first digit no longer decides. Should 3 come before 30, or 30 before 3?

The simplest way to find out is to try both. Look at the picture below. On the left, the cards 3 and 30 are glued both ways: 3 then 30 reads 330, and 30 then 3 reads 303. 330 is bigger, so 3 goes first. On the right, 34 then 3 reads 343, which beats 334, so 34 goes before 3.

Gluing 3 and 30 both ways gives 330 and 303, so 3 goes first. Gluing 34 and 3 both ways gives 343 and 334, so 34 goes first. In that order, 9, 5, 34, 3, 30 reads 9534330.

In the bottom row, every pair of cards is in its winning order, the one that reads bigger: 9, 5, 34, 3, 30. Read together, that is 9534330, the answer to Example 2. Example 1 works the same way: 2 then 10 reads 210, which beats 102.

So the whole row comes down to one small question about two cards at a time: glued together, which order gives the bigger number? Sorting the cards with that question as the rule for "comes first" puts every card in its place.

Solution Approach

Turning that idea into code means settling four things: how to compare two numbers, why a sort with that comparison builds the best row, how to write the comparison in Java, and what to return when every number is 0.

Comparing two numbers

Why not simply sort the numbers from largest to smallest? Because a number's size says little about its first digit. Sorted by value, [10, 2] puts 10 first and reads 102, which is smaller than 210.

Sorting the numbers as text, largest first, is closer. Text is compared character by character from the left, so "2" beats "10" because 2 beats 1. But when one number is the start of another, as 3 is the start of 30, text order puts the longer one first. [3, 30, 34, 5, 9] then reads 9534303 instead of 9534330.

The same happens with 824 and 8247: text order gives 8247824, but 824 first gives 8248247, which is bigger. Gluing both ways settles every case, because it compares exactly the two rows the pair can form.

Why sorting builds the best row

Is deciding two cards at a time enough to get the whole row right? Suppose two neighbouring cards are in their losing order, the one that reads smaller. Swapping them changes only their own stretch of digits, and that stretch gets bigger, so the whole number gets bigger.

So the largest row has no neighbours in their losing order, and that is exactly what a sort with this rule produces. The rule is also consistent: if a goes before b, and b goes before c, then a goes before c. A sort relies on that to put all the items in one order.

Writing the comparison in Java

How do we hand this rule to Java's sort? First, each number becomes a string with String.valueOf, so gluing two of them is just a + b. Arrays.sort then takes a comparator: a small function that gets two items, a and b, and returns a negative number when a should come first, a positive number when b should, and 0 when either order is fine.

The comparator here is (b + a).compareTo(a + b). String.compareTo compares two strings character by character. a + b and b + a have the same length, so the string that is larger as text is also the larger number. When a + b is bigger, the result is negative, and a goes first.

Strings have a second benefit: the numbers are never added or multiplied, so nothing can overflow, that is, grow past the largest value a type can hold. Two copies of 1,000,000,000 make a 20-digit answer, more than even a Java long can hold.

When every number is 0

What if all the numbers are 0? [0, 0, 0] glues to "000", but the number is just 0. After the sort, the card that must come first is at the front, so if the first string is "0", every card is 0 and the answer is "0". A single other number avoids this: [0, 0, 1] gives "100".

Java Solution

The method largestNumber works in these steps:

  1. First, turn the numbers into strings: create the array parts, the same size as nums, and fill it with String.valueOf(nums[i]) in a loop.
  2. Sort parts with Arrays.sort and the comparator (a, b) -> (b + a).compareTo(a + b), so a string goes first when gluing it in front makes the bigger number.
  3. Check the first string. If parts[0] is "0", every number was 0, so return "0".
  4. Otherwise, glue all the strings together with String.join("", parts) and return the result.

The main method runs both examples, the pair 824 and 8247, three zeros, two zeros with a 1, and two numbers of one billion.

Java
import java.util.Arrays;

public class LargestNumber {

    public static String largestNumber(int[] nums) {
        String[] parts = new String[nums.length];
        for (int i = 0; i < nums.length; i++) {
            parts[i] = String.valueOf(nums[i]);
        }
        // a goes before b if a + b makes a bigger number than b + a
        Arrays.sort(parts, (a, b) -> (b + a).compareTo(a + b));
        if (parts[0].equals("0")) {
            return "0";                       // all zeros: "0", not "000"
        }
        return String.join("", parts);
    }

    public static void main(String[] args) {
        System.out.println(largestNumber(new int[] {10, 2}));
        System.out.println(largestNumber(new int[] {3, 30, 34, 5, 9}));
        System.out.println(largestNumber(new int[] {824, 8247}));
        System.out.println(largestNumber(new int[] {0, 0, 0}));
        System.out.println(largestNumber(new int[] {0, 0, 1}));
        System.out.println(largestNumber(new int[] {1000000000, 1000000000}));
    }
}

Running it prints:

Output
210
9534330
8248247
0
100
10000000001000000000

The first two lines, 210 and 9534330, answer the two examples. The third line, 8248247, puts 824 before 8247, the order that sorting as plain text gets wrong. The fourth line is a single 0 rather than 000, thanks to the check on parts[0].

The fifth line shows that the zeros only shrink to one when every number is 0: [0, 0, 1] gives 100. The last line has 20 digits, more than a long can hold, and it still comes out right because the method only glues strings.

The original implementation, LargestNumber.java, is on GitHub.

Complexity

The work is the sort, and every comparison inside it builds two glued strings.

  • Time: O(n log n × d), where n is the number of values and d the most digits any of them has. The sort makes O(n log n) comparisons, and each builds and compares strings of up to 2d characters. Turning the numbers into strings and joining them adds only O(n × d).
  • Space: O(n × d). parts holds n strings of up to d digits, and the answer has up to n × d characters. Each comparison makes two short temporary strings.

A comparator that decides which of two items comes first also drives Queue Reconstruction by Height.