algoadvance

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.

Examples:

  1. Input: nums = [10, 2] Output: "210"

  2. Input: nums = [3, 30, 34, 5, 9] Output: "9534330"

Constraints:

Clarifying Questions:

  1. Q: Can the numbers in the list be very large? A: Yes, that’s why the final result has to be a string.

  2. Q: Should the solution handle cases with leading zeros in the output? A: Yes, the solution should handle and remove any unnecessary leading zeros.

  3. Q: What should the function return if all elements in the list are zeros? A: It should return “0”.

Strategy:

  1. Custom Sorting: The primary challenge is the sorting order. To decide the order between two numbers, compare the concatenation results of both possible orders. For example, to decide between 3 and 30, compare 330 (3+30) and 303 (30+3). Since 330 is greater, 3 should come before 30.
  2. String Conversion: Convert the integers to strings for easy concatenation and comparison.
  3. Sorting Implementation: Use Python’s built-in sorting functions with a custom comparator based on the concatenation result.
  4. Edge Handling: After sorting and concatenation, handle any leading zeros by converting the final result to an integer and back to string.

Code:

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"

Time Complexity:

Overall, the algorithm runs in (O(n \log n)) time complexity, which is efficient given the constraints.

Try our interview co-pilot at AlgoAdvance.com