Visualize

Pattern visualizer

Largest Number

Sorting the numbers by their own value is the trap: 3 is smaller than 30, yet 3 belongs first, because 330 beats 303. Size is the wrong question. The only question that matters between two values is which order reads larger when they are glued together, so that comparison IS the sort key: a comes before b when a+b > b+a as text. That rule is consistent across the whole list, which is why one sort settles every slot at once and no later rearrangement can improve the total. The single exception is an input of nothing but zeros, where the join reads 000 and has to be reported as 0. Animated on: nums = [3, 30, 34, 5, 9, 35]. Arrange every number end to end so the resulting number is as large as possible..

Sort by which pair reads bigger, not by size

time O(n log n * L)space O(n * L)step 1 / 15
3
[0]
30
[1]
34
[2]
5
[3]
9
[4]
35
[5]
line 2

Plain numeric order would put 35, 34, 30, 9, 5, 3 on the page, and that is wrong: it reads 353430953. What decides the answer is never a number's size but how a PAIR reads glued together — so the whole sort runs on "3" + "30" against "30" + "3".

Pseudocode
1FUNCTION largestNumber(nums)
2 s <- STRINGS(nums)
3 FOR i <- 0 TO LENGTH(s) - 2
4 best <- i
5 FOR j <- i + 1 TO LENGTH(s) - 1
6 IF CONCAT(s[j], s[best]) > CONCAT(s[best], s[j])
7 best <- j
8 SWAP s[i], s[best]
9 IF s[0] = "0"
10 RETURN "0"
11 RETURN JOIN(s)

← / → step · space play · Home restart

Where to practice Greedy