sort
greedy
]
Leetcode 0179. Largest Number
https://leetcode.com/problems/largest-number
Note, that we need to somehow sort our data, but be carefull about it: if we have 3
, 32
and 31
, then we need to choose 3
as the first element. However if we have 3
, 34
and 32
, then we need to chose 34
as the first element. So, let us for each two numbers x
and y
decide which one is better: we need to compare xy
and yx
and choose the best one: we work with x
and y
as with strings: for example for x = 3
and y = 32
, we need to compare xy = 332
and yx = 323
. Also it can be shown that if xy >= yx
and yz >= zy
, then xz >= zx
, this means that we have transitivity property, and this is enough to ensure that our sort is consistent: https://en.wikipedia.org/wiki/Comparison_sort
Complexity: time complexity is O(n log n)
, if we assume that we can make comparison in constant time. In practise, we use strings and compare them, so complexity will be ineed O(1)
. Space complexity is O(n)
to keep sorted numbers.
Note I use cmp_to_key
function from functools
library, which is imported in leetcode already. Also in the end we can have results like 00
, which we need to make 0
, so we use str(int(...))
trick.
class Solution:
def largestNumber(self, nums):
compare = lambda a, b: -1 if a+b > b+a else 1 if a+b < b+a else 0
return str(int("".join(sorted(map(str, nums), key = cmp_to_key(compare)))))
If you like the solution, you can upvote it on leetcode discussion section: Problem 0179