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
Example 1
Output: "210"
Example 2
Output: "9534330"
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.
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]
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]
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.valueOfa + bArrays.sortabab
The comparator here is (b + a).compareTo(a + b)String.compareToa + bb + aa + ba
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
When every number is 0
What if all the numbers are 0? [0, 0, 0][0, 0, 1]
Java Solution
The method largestNumber
- First, turn the numbers into strings: create the array
, the same size asparts , and fill it withnums in a loop.String.valueOf(nums[i]) - Sort
withparts and the comparatorArrays.sort , so a string goes first when gluing it in front makes the bigger number.(a, b) -> (b + a).compareTo(a + b) - Check the first string. If
is "0", every number was 0, so return "0".parts[0] - Otherwise, glue all the strings together with
and return the result.String.join("", parts)
The main
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:
210
9534330
8248247
0
100
10000000001000000000
The first two lines, 2109534330parts[0]
The fifth line shows that the zeros only shrink to one when every number is 0: [0, 0, 1]long
The original implementation,
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).
holds n strings of up to d digits, and the answer has up to n × d characters. Each comparison makes two short temporary strings.parts
A comparator that decides which of two items comes first also drives