Space
Open
From Fieldwork
Scales
Archive
We can notice that this is a prefix comparison problem.
class Solution:
from functools import cmp_to_key
def largestNumber(self, nums):
# Convert numbers to strings
num_strs = [str(num) for num in nums]
# Custom comparator
def compare(a, b):
if a + b > b + a:
return -1 # a should come first
else:
return 1 # b should come first
# Sort with the custom rule
num_strs.sort(key=cmp_to_key(compare))
# Join strings together
result = "".join(num_strs)
# Handle the "000" edge case by converting to int and back to str
# Or simply: return '0' if result[0] == '0' else result
# if parts and parts[0] == "0":
# return "0"
return str(int(result))Practice bench
A private scratchpad for this reading. Nothing is sent or scored.
What is still unclear, or what would change the explanation?
Saved on this device · one draft per mode