Magicsheet logo

Largest Number

Medium
75%
Updated 6/1/2025

Largest Number

1. What is this problem about?

The Largest Number coding problem asks you to take a list of non-negative integers and arrange them in such a way that they form the largest possible number when concatenated. Because the result can be very large, it is typically returned as a string. For instance, given [10, 2], the largest number is "210" rather than "102".

2. Why is this asked in interviews?

This is a quintessential interview question asked by nearly every major tech company, including Google, Meta, and Apple. It tests your ability to define custom sorting criteria. Standard numerical or alphabetical sorting won't work here. The problem requires you to think about how different numbers interact when placed side-by-side, making it an excellent test of logical reasoning and comparator implementation.

3. Algorithmic pattern used

The core pattern is the Sorting and Greedy interview pattern. The trick is to define a custom comparator for the numbers. Instead of comparing a and b directly, you compare the concatenations: a + b vs b + a. If a + b is greater, then a should come before b in our sorted list. This greedy strategy ensures that every local pair is optimized, leading to the overall largest concatenated string.

4. Example explanation

Take the numbers: [3, 30, 34]. Compare 3 and 30: "330" > "303", so 3 comes before 30. Compare 30 and 34: "3430" > "3034", so 34 comes before 30. Compare 3 and 34: "343" > "334", so 34 comes before 3. Sorted order: [34, 3, 30]. Concatenated: "34330". This is the largest possible combination.

5. Common mistakes candidates make

A very common mistake is sorting numbers alphabetically (where "30" might come before "3"). Another is not handling the edge case where the input is a list of zeros (e.g., [0, 0]). The result should be "0", not "00". Candidates also sometimes struggle with the syntax of custom comparators in their chosen programming language.

6. Interview preparation tip

For "Array, Sorting, String interview pattern" questions, always clarify the result type. If it's a concatenated string, think about how string comparison works compared to integer comparison. Practice writing custom sort functions (like sort() with a lambda in Python or Comparator in Java) until it becomes second nature.

Similar Questions