Largest Number

Medium · Arrays & Hashing · Array · String · Greedy · Sorting

Problem

You are given a list of non-negative integers nums. Arrange them so that, written one after another, they form the largest possible number, and return that number as a string. The result can be far too big for any integer type.

The answer must not have leading zeros: if every number is 0, return "0".

Examples

Input: nums = [5,56,9]
Output: "9565"

9 leads, and 56 goes before 5 because "565" > "556".

Input: nums = [12,121]
Output: "12121"

"12121" beats "12112", so 12 goes first.

Input: nums = [0,0,0]
Output: "0"

Leading zeros collapse to a single "0".

Constraints

Approaches

Follow-up

Why is the comparison "a + b > b + a" transitive? Write each piece as a number and show that the rule is the same as comparing a / (10^len(a) - 1) with b / (10^len(b) - 1), an ordinary order on real numbers.

Related problems

Start free on Cariara · Coding problems · System design studio

Starting Python
No results yet.

          
↑↓ move ↵ open esc close

Labs

Loading labs…

Run with your own input

Starting Python

Loading Python…