MediumNo. 0179
Largest Number — LeetCode 179 Python Solution
- Pattern
- Greedy
- Topics
- Greedy, Array, String, Sorting
- 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
- Time
- O(n log n)
- Space · auxiliary
- O(1) to O(n)
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
| No. | Problem | Difficulty |
|---|---|---|
| 1946 | Largest Number After Mutating Substring | Medium |
| 0747 | Largest Number At Least Twice of Others | Easy |
| 2231 | Largest Number After Digit Swaps by Parity | Easy |
| 0324 | Wiggle Sort II | Medium |
| 0452 | Minimum Number of Arrows to Burst Balloons | Medium |
| 0455 | Assign Cookies | Easy |
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.