Largest Number — LeetCode 179 Python Solution

MediumGreedyArrayStringSorting
Problem
#179
Pattern
Greedy
Reading time
2 min

The problem

Given a list of non-negative integers nums, arrange them such that they form the largest number and return it. Since the result may be very large, so you need to return a string instead of an integer.

Example

Input
nums = [10,2]
Output
"210"

Python solution

Python
class Solution:
    def largestNumber(self, nums: List[int]) -> str:
        nums = [str(v) for v in nums]
        nums.sort(key=cmp_to_key(lambda a, b: 1 if a + b < b + a else -1))
        return "0" if nums[0] == "0" else "".join(nums)

Complexity

MeasureComplexity
TimeO(n log n)
SpaceO(1) to O(n) auxiliary

Pattern: Greedy

Take the locally best option every time — when you can prove that never costs you later. LeetCode 179. Largest Number is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Greedy.

The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 179. Largest Number?
LeetCode 179. Largest Number is rated Medium on LeetCode.
What topics does LeetCode 179. Largest Number cover?
LeetCode 179. Largest Number is tagged Greedy, Array, String and Sorting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview