Largest Number

You are given a list of non-negative integers nums. Arrange them in some order and write them one after another, with no separators, to form a single number. For example, the order [34, 5] produces 345 and the order [5, 34] produces 534.

Return the largest number that can be produced this way. Because it can be far too long for any integer type, return it as a string. The result must not have leading zeros, so if every possible arrangement is made only of zeros, return "0".

Example 1

Input: nums = [34,5] Output: "534" Why: 5 goes first, then 34, giving 534 rather than 345.

Example 2

Input: nums = [8,90,1,84,9] Output: "9908841" Why: 9 comes before 90 because 990 > 909, and 8 comes before 84 because 884 > 848. The order 9, 90, 8, 84, 1 gives 9908841.

Example 3

Input: nums = [0,0,0] Output: "0" Why: All values are zero, so the answer is the single digit "0", not "000".

Constraints

  • 1 <= nums.length <= 100
  • 0 <= nums[i] <= 109

Pattern Path · Intervals & Greedy · problem 115 of 169

Sorting by numeric value fails (10 would come before 9). Sorting the decimal strings in descending order also fails for some pairs: compare 3 and 30. Why?
Focus on just two numbers a and b. Which one should come first in the final answer?
Put a before b exactly when the string a + b is larger than b + a. Sort with that comparison and join. Watch for an all-zero input.
Target: O(n log n · d), d = digits per number time, O(n · d) extra space.

Start simple

Try every permutation, concatenate, and keep the largest: O(n!·L) time for n numbers of total length L.

The key idea

Decide the order one pair at a time. For two numbers written as strings a and b, the only two ways to place them next to each other are a+b and b+a. Both have the same length, so comparing them as strings tells you which order is better for that pair.

Sort with the rule "a goes first if a+b > b+a". This comparison is consistent (it is transitive), so sorting produces a single global order. In that order no adjacent pair can be swapped to make the number bigger, and an exchange argument shows that any arrangement that disagrees with it can be improved by such a swap. So the sorted order is optimal.

The comparator is what makes cases like 3 vs 30 work: 330 > 303, so 3 goes first even though 30 is larger and also beats 3 in plain string order.

Finally, if the first element after sorting is "0", every element is zero, so return "0" instead of a run of zeros.

Complexity

  • Time: O(n log n · d), d = digits per number
  • Space: O(n · d)

Python

from functools import cmp_to_key

class Solution:
    def largestNumber(self, nums):
        strs = [str(x) for x in nums]

        def compare(a, b):
            # Negative means "a goes first": choose the order whose concatenation is larger.
            if a + b > b + a:
                return -1
            if a + b < b + a:
                return 1
            return 0

        strs.sort(key=cmp_to_key(compare))
        if strs[0] == "0":          # the largest piece is 0, so every piece is 0
            return "0"
        return "".join(strs)

JavaScript

var largestNumber = function(nums) {
  const strs = nums.map(String);
  // a goes before b when a+b forms the larger string (both have equal length).
  strs.sort((a, b) => {
    const ab = a + b, ba = b + a;
    if (ab > ba) return -1;
    if (ab < ba) return 1;
    return 0;
  });
  if (strs[0] === "0") return "0";   // the largest piece is 0, so every piece is 0
  return strs.join("");
};

What the interviewer is checking

It tests whether you can design a custom comparator, justify that it gives a correct total order, and catch the all-zero edge case.

Mistakes to avoid

  • Sorting strings in reverse lexicographic order, which wrongly puts 30 before 3.
  • Returning "000" for an input of all zeros.
  • Converting the result to an integer, which overflows or loses precision for long answers.
  • Writing a comparator that returns a boolean where the language expects a negative/zero/positive number (JavaScript, Python cmp_to_key).

Follow-ups to expect

  • How would you build the smallest number instead? (Flip the comparator, strip zeros.)
  • Why is the comparator transitive? (Concatenation compares like a/(10^len-1) values.)
  • Can you avoid building strings? (Compare using digit counts and arithmetic.)

In real software

Custom sort keys built from pairwise rules appear in ranking feeds, ordering version strings and building canonical identifiers from parts.

Practice next

Next Post Previous Post
No Comment
Add Comment
comment url