Largest Number — LeetCode 179 Python Solution
- Problem
- #179
- Pattern
- Greedy
- Reading time
- 2 min
- Source
- leetcode.com
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
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
| Measure | Complexity |
|---|---|
| Time | O(n log n) |
| Space | O(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.