The problem. Given a list of non-negative integers, arrange them so that, written one after another, they form the largest possible number. Return it as a string (it may be too big for any integer type).
nums = [10, 2] -> "210"
nums = [3, 30, 34, 5, 9] -> "9534330"
nums = [0, 0] -> "0"Numeric order doesn't work (9 must come before 30), and neither does plain string order ("3" vs "30" is ambiguous). The right question for any two values a and b is: which order of the two makes the bigger number? Compare the strings a + b and b + a — they have the same length, so comparing them as strings compares them as numbers. Put a first if a + b is bigger.
This comparison is consistent (transitive), so a normal sort with it produces an order where every neighbouring pair is in its best order — and that is the largest number overall. One last detail: if the biggest piece is "0", every value is 0, and the answer is "0", not "000".
function largestNumber(nums) { const strs = nums.map(String); let best = ""; const used = new Array(strs.length).fill(false); const build = (cur, count) => { if (count === strs.length) { if (cur > best) best = cur; // same length, so string order is number order return; } for (let i = 0; i < strs.length; i++) { if (used[i]) continue; used[i] = true; build(cur + strs[i], count + 1); used[i] = false; } }; build("", 0); return best[0] === "0" ? "0" : best;}Time O(n! · n·k), space O(n·k). Every one of the n! orders is built and compared — fine for 8 values, hopeless for 100.
Each comparison glues the two values both ways; the bigger result decides the order.
function largestNumber(nums) { const strs = nums.map(String); strs.sort((a, b) => (b + a > a + b ? 1 : b + a < a + b ? -1 : 0)); // a first if a+b is the bigger number if (strs[0] === "0") return "0"; // every value was 0 return strs.join("");}Time O(n log n · k), space O(n·k) for numbers of up to k digits: each comparison builds two strings of length up to 2k.
[0, 0] gives "0".3 vs 30 vs 34: the comparator handles them; plain string sorting puts 30 before 34 but gets 3 vs 30 wrong.12 and 1212 compare equal; either order is fine.