Given a list of non-negative integers, arrange them so that they form the largest number when concatenated, and return it as a string.
Before you code
Sorting by numeric value fails ([10, 2] should give "210"), and sorting the strings in reverse lexicographic order fails too ([3, 30]: "330" beats "303"). The right order compares two numbers by which concatenation is bigger.
Hints
- Convert to strings. Put
abeforebwhena + b > b + aas strings. - That comparison is a valid total order (it is transitive), which is what a sort requires. Convince yourself with
3,30and34. - In Python, use
functools.cmp_to_key; in Java, aComparator<String>. - If the result starts with "0", every number was 0: return "0", not "00".
Production & complexity notes
When solving Largest number on LeetCode (medium), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Stability and what libraries use to reinforce the underlying pattern.
What it practices
Writing a comparator that defines a consistent order, from Stability and what libraries use.