Foundations

Largest Number

Custom sort comparator: compare string concatenations in both orders to determine which arrangement of two numbers produces the larger value.

mediumFree~15 min

Problem

A financial reporting tool needs to display account balances as the largest possible combined value by reordering the figures. Given a list of non-negative integers, arrange them to form the largest possible number and return it as a string.

Input: [10, 2]          -> "210"
Input: [3, 30, 34, 5, 9] -> "9534330"
Input: [0, 0]           -> "0"

Solution

Approach: Custom comparator sort via functools.cmp_to_key.

The largest concatenation is built by sorting the numbers under a pairwise rule rather than by their numeric value. For any two numbers a and b, a should come before b exactly when the string str(a) + str(b) is lexicographically larger than str(b) + str(a) - that is, when putting a first yields the bigger combined number. The compare(a, b) function returns -1 in that case (a precedes b) and 1 otherwise, and cmp_to_key wraps it so sorted can apply it. Once every adjacent pair satisfies this relation, joining the numbers left to right produces the maximum possible number. Trace [3, 30, 34, 5, 9]: comparing 3 and 30 gives "330" > "303", so 3 precedes 30; comparing 9 against everything wins, so 9 leads. The sort settles to [9, 5, 34, 3, 30], which joins to "9534330".

Why a comparator and not a key= function: the decision depends on both elements at once (a+b vs b+a), a relation no per-element key can capture. The comparator is transitive, so the global sort is well defined. String comparison naturally handles different lengths - "9" > "30" because '9' > '3' at position 0 - which is exactly the ordering this problem needs.

Edge cases: All zeros - [0, 0] joins to "00", so the leading-zero check "0" if result[0] == "0" else result collapses it to "0". A single element returns its own digits.

Complexity: O(nk log n) time, O(n) space - n log n comparisons, each comparing two k-digit strings; the output and decorated list are O(n).

Done reading? Mark it so it sticks in your dashboard.

Next in CodingSort List

Discussion (0)

Sign in to join the discussion.
No comments yet. Start the discussion.