You are 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, you need to return a string representation of the number.
Input: nums = [10, 2]
Output: "210"
Input: nums = [3, 30, 34, 5, 9]
Output: "9534330"
1 <= nums.length <= 100
0 <= nums[i] <= 109
Q: Can the numbers in the list be very large? A: Yes, that’s why the final result has to be a string.
Q: Should the solution handle cases with leading zeros in the output? A: Yes, the solution should handle and remove any unnecessary leading zeros.
Q: What should the function return if all elements in the list are zeros? A: It should return “0”.
3
and 30
, compare 330
(3+30) and 303
(30+3). Since 330
is greater, 3
should come before 30
.from functools import cmp_to_key
def largestNumber(nums):
# Custom comparator function
def compare(x, y):
if x + y > y + x:
return -1
elif x + y < y + x:
return 1
else:
return 0
# Convert integers to strings
str_nums = list(map(str, nums))
# Sort based on custom comparator
str_nums.sort(key=cmp_to_key(compare))
# Join sorted strings
largest_num = ''.join(str_nums)
# Handle leading zeros
return '0' if largest_num[0] == '0' else largest_num
# Example usage:
nums1 = [10, 2]
print(largestNumber(nums1)) # Output: "210"
nums2 = [3, 30, 34, 5, 9]
print(largestNumber(nums2)) # Output: "9534330"
0 <= nums[i] <= 10^9
and each number is concatenated at most twice).Overall, the algorithm runs in (O(n \log n)) time complexity, which is efficient given the constraints.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?