179. Largest Number LeetCode Solution

In this guide, you will get 179. Largest Number LeetCode Solution with the best time and space complexity. The solution to Largest Number problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Largest Number solution in C++
  4. Largest Number solution in Java
  5. Largest Number solution in Python
  6. Additional Resources
179. Largest Number LeetCode Solution image

Problem Statement of Largest Number

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, so you need to return a string instead of an integer.

Example 1:

Input: nums = [10,2]
Output: “210”

Example 2:

Input: nums = [3,30,34,5,9]
Output: “9534330”

Constraints:

1 <= nums.length <= 100
0 <= nums[i] <= 109

Complexity Analysis

  • Time Complexity: O(\texttt{sort})
  • Space Complexity: O(n)

179. Largest Number LeetCode Solution in C++

class Solution {
 public:
  string largestNumber(vector<int>& nums) {
    string ans;

    ranges::sort(nums, [](int a, int b) {
      return to_string(a) + to_string(b) > to_string(b) + to_string(a);
    });

    for (const int num : nums)
      ans += to_string(num);

    return ans[0] == '0' ? "0" : ans;
  }
};
/* code provided by PROGIEZ */

179. Largest Number LeetCode Solution in Java

class Solution {
  public String largestNumber(int[] nums) {
    final String s = Arrays.stream(nums)
                         .mapToObj(String::valueOf)
                         .sorted((a, b) -> (b + a).compareTo(a + b))
                         .collect(Collectors.joining(""));
    return s.startsWith("00") ? "0" : s;
  }
}
// code provided by PROGIEZ

179. Largest Number LeetCode Solution in Python

class LargerStrKey(str):
  def __lt__(x: str, y: str) -> bool:
    return x + y > y + x


class Solution:
  def largestNumber(self, nums: list[int]) -> str:
    return ''.join(sorted(map(str, nums), key=LargerStrKey)).lstrip('0') or '0'
# code by PROGIEZ

Additional Resources

Happy Coding! Keep following PROGIEZ for more updates and solutions.