Largest Number solution explained
The Largest Number solution turns every integer into a string and sorts with one comparison: put a before b when a + b, read as text, is bigger than b + a. Join the sorted strings, and return "0" if the result starts with a zero. It runs in O(n log n) comparisons, each costing as much as the digits involved.
By Evin JohnPublished 7 min read
The problem in plain terms
You have a list of non-negative whole numbers. Write them one after another, in any order you like, to form a single long number. Return the largest number you can form, as a string, because it can easily be longer than any integer type can hold.
| Numbers | Largest result | Point it makes |
|---|---|---|
| [4, 45, 9] | 9454 | 45 goes before 4 because 454 beats 445. |
| [8, 80, 81] | 88180 | 8 goes first: 880 beats 808 and 881 beats 818. |
| [12, 121] | 12121 | 12 goes first, even though 121 is the bigger number and the longer string. |
| [10, 2] | 210 | A smaller number can lead if its first digit is larger. |
| [0, 0, 0] | 0 | Never return a string of several zeros. |
Ask whether the list can be empty and whether negative numbers can appear. Most versions say at least one number and no negatives. With negatives the question stops making sense, so confirm it.
Why it comes up
This problem tests custom ordering. Most candidates know how to call a sort; fewer can design a comparator and explain why the result is consistent. It also hides two traps, the leading-zero case and integer overflow, that catch people who rush to code.
Slow approach: every arrangement
The direct method lists every ordering, joins each one, and keeps the biggest. With n numbers there are n! orderings, so it only works for tiny inputs. It is still the cleanest correctness oracle you can write, and Python's big integers make the comparison easy.
from itertools import permutations
def biggest_join_search(nums):
best = max(int("".join(map(str, order))) for order in permutations(nums))
return str(best)Two sorts that look right and are not
- Sort by value, largest first. For [10, 2] it gives 102, but 210 is bigger. Size of the number is the wrong signal.
- Sort the strings in reverse dictionary order. For [8, 80] it puts "80" ahead of "8" and gives 808, but 880 is bigger. For [12, 121] it puts "121" first and gives 12112, while 12121 is bigger.
Both failures involve one number being a prefix of another, or numbers of different lengths. Dictionary order cannot know what follows the shorter string once it is placed. The fix is to compare the two complete outcomes directly.
Main approach: compare a + b with b + a
For two strings a and b, only two arrangements of the pair exist: a + b and b + a. Both have the same length, so a plain string comparison tells you which is the bigger number. Put a first if a + b wins. Sort the whole list with that rule and join it. If the first character is '0', every number was zero, so return "0".
Is a sort allowed to use this rule? A comparison sort needs the rule to be transitive: if a should precede b and b should precede c, then a should precede c. Write a with length p digits as the number A. The join a + b equals A times 10 to the power len(b), plus B. Comparing a + b with b + a then reduces to comparing A divided by (10 to the power p minus 1) with the same quantity for b. That ratio is a single real number per string, and ordering by a fixed number per item is always transitive. In practice you can say: the comparator agrees with sorting by a hidden numeric key, so the sort is sound.
from functools import cmp_to_key
def biggest_join(nums):
parts = [str(x) for x in nums]
parts.sort(key=cmp_to_key(lambda a, b: (b + a > a + b) - (b + a < a + b)))
return "".join(parts).lstrip("0") or "0"function biggestJoin(nums) {
const parts = nums.map(String);
parts.sort((a, b) => {
const ab = a + b;
const ba = b + a;
if (ab > ba) return -1;
if (ab < ba) return 1;
return 0;
});
return parts.join("").replace(/^0+/, "") || "0";
}Trace [8, 80, 81]. Comparing 8 with 80 gives 880 against 808, so 8 first. Comparing 81 with 80 gives 8180 against 8081, so 81 before 80. Comparing 8 with 81 gives 881 against 818, so 8 first. The sorted order is 8, 81, 80 and the answer is 88180.
Complexity
| Method | Time | Space |
|---|---|---|
| All orderings | O(n! · n · d) | O(n · d) |
| Sort with the join comparator | O(n log n · d) | O(n · d) for the strings |
Each comparison builds two strings of up to 2d characters, so it is O(d), not O(1). With values bounded by a typical 32-bit range, d is at most ten and people often call the whole thing O(n log n). Say which one you mean.
Edge cases
- A single number: return it as a string.
- All zeros: return "0".
- Zeros mixed with others, like [0, 5]: the zero sinks to the end and the answer is 50.
- Repeated prefixes such as [9, 99, 999]: every comparison ties, any order works, and the answer is all nines.
- Very long outputs: keep the result as a string. Converting to a JavaScript number loses precision beyond 2^53, and fixed-width integers in Java or C++ overflow far sooner.
Common slips
- Returning a boolean from a JavaScript comparator. The sort expects a negative, zero or positive number, and a boolean gives inconsistent orderings.
- Passing a cmp argument to sorted in Python 3. It was removed; use functools.cmp_to_key.
- Forgetting the all-zero case and returning "000".
- Converting the final string to an integer to strip zeros, which overflows in many languages.
- Claiming the comparator is obviously transitive. Have the ratio argument, or at least a sketch of it, ready.
Follow-up directions
- Smallest number instead. Flip the comparator, then strip leading zeros carefully, keeping a single zero if nothing else remains.
- Avoid building strings in each comparison. Precompute each number's digit length and compare a times 10 to the power len(b) plus b numerically, using big integers where needed.
- Pick k of the numbers to form the largest result. That is a different problem and needs more than one sort.
Explaining your choice
Fictional example
- Candidate
- Sorting by value fails on 10 and 2, and reverse string order fails on 8 and 80, so I compare the two joins of each pair directly.
- Candidate
- If a plus b as text beats b plus a, a goes first. That rule matches sorting by a hidden numeric key, so it is transitive and a normal sort is safe.
- Candidate
- Then I join the strings, and if the first character is zero I return a single zero. It is n log n comparisons, each linear in the digit count.
Keep going
Largest Time for Given Digits is the natural next step, since it also builds the biggest value from given digits but adds clock limits. Break a Palindrome practices the same reasoning about dictionary order from the other direction, aiming for the smallest result. For more comparator and sorting questions, see the algorithm interview questions.
Using Natively while you study
Natively can read a screenshot of a sorting problem during practice and suggest an approach and code, which helps when you want a second opinion on a comparator after writing your own. A transcript of your mock interview, recorded on your computer, lets you check later whether you explained transitivity or just asserted it. Read about an AI interview assistant built for Mac and Windows.
Questions people ask
How do you solve the Largest Number problem?
Convert every number to a string and sort so that a comes before b whenever a + b is greater than b + a as text. Join the result, and return "0" if it starts with a zero.
Why doesn't sorting the strings in reverse order work?
Plain string order mishandles prefixes. For 8 and 80 it puts 80 first and builds 808, while 880 is larger. Comparing the two joins avoids that.
Is the a + b versus b + a comparator transitive?
Yes. Comparing the joins is the same as comparing each number divided by (10 to the power of its digit count, minus 1), which is one fixed value per number, so the ordering is consistent.
What is the time complexity?
O(n log n) comparisons, each linear in the number of digits, plus O(n) space for the strings. With bounded integers that is usually quoted as O(n log n).
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
