Similar Problems

Similar Problems not available

Largest Number - Leetcode Solution

LeetCode:  Largest Number Leetcode Solution

Difficulty: Medium

Topics: greedy string sorting array  

Problem Statement: Given a list of non-negative integers, arrange them such that they form the largest number.

Example:

Input: [3,30,34,5,9] Output: "9534330"

Solution: To solve this problem, we need to create a custom sort function. Sort the numbers in the decreasing order based on the following comparison:

For any two numbers a and b, we compare the concatenation of a and b to the concatenation of b and a. If the former is greater than the latter, then a should come before b in the sorted array.

For example:

a=3, b=30

concatenation of a and b = "330"

concatenation of b and a = "303"

Since "330" is greater than "303", a should come before b in the sorted array.

Using this custom sort, we can sort the list of numbers in descending order to form the largest number. Once we have sorted the numbers, we concatenate them to form the final result.

Code:

Here's the Python code to solve this problem:

class Solution: def largestNumber(self, nums: List[int]) -> str: nums = [str(num) for num in nums] nums.sort(key=lambda x: x + x[0], reverse=True) return str(int(''.join(nums)))

Largest Number Solution Code

1