#179

Largest Number

Medium Comparator on concatenation

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Arrange non-negative integers so that, written side by side, they form the largest possible number. Return it as a string.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: arrange numbers to form the biggest possible number.

Why this works: compare two numbers by gluing them both ways: put a first if a + b > b + a as strings.

Example: [3, 30, 34, 5, 9]

"9" first, then "5", then "34" ("343" > "334")"3" before "30" ("330" > "303")"9534330"

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Returning "000" for all-zero input instead of "0".

Solve on LeetCode ↗
Complexity
  • Time: O(n log n · k), k = digits per number.
  • Space: O(n · k).
Topic: Sorting
🎬 Episodes 24–28: video coming soon