The Indian Engineer

Problem 179 Largest Number

Posted on 5 mins

Array String Greedy Sorting

Problem Statement

Link - Problem 179

Question

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:

Solution

class Solution {
public:
    static bool compare(string sa, string sb) {
        if((sa + sb )> (sb + sa)){
            return true;
        }
        return false;
    }

    string largestNumber(vector<int>& nums) {
        vector<string>n;
        for(auto it:nums)
            n.push_back(to_string(it));

        sort(n.begin(), n.end(), compare);

        if (n[0] == "0") {
            return n[0];
        }

        string ans = "";
        for (auto num : n) {
            ans += num;
        }

        return ans;
    }
};

Complexity Analysis

| Algorithm      | Time Complexity | Space Complexity |
| -------------- | --------------- | ---------------- |
| Custom Sorting | O(n log n)      | O(n)             |

Explanation

Intial Thoughts

First, understand the goal of forming the largest number from a list of non-negative integers. Think about comparing numbers in a way that considers their potential as part of a larger number. Consider that numbers should be compared based on their contribution to the overall number, not just their individual size. Think about the role of sorting and how it can be customized to achieve the desired outcome. Consider how to handle the case when all numbers are 0.

Intuitive Analysis

To intuitively solve this problem, think of it as arranging words in a dictionary where each word represents a number. Compare these ‘words’ based on which one comes first when concatenated with another. Consider the impact of leading digits and how they affect the overall size of the number. Imagine using a custom sorting method that takes into account the concatenation of numbers. Think about how to identify and handle edge cases efficiently, such as when the largest number is 0. Consider the importance of string manipulation in solving the problem.

1. Intuition

2. Implementation


Complexity Analysis

Time Complexity:

Space Complexity:


Footnote

This question is rated as Medium difficulty.


Similar Questions:

Title URL Difficulty
Smallest Value of the Rearranged Number https://leetcode.com/problems/smallest-value-of-the-rearranged-number Medium
Find the Key of the Numbers https://leetcode.com/problems/find-the-key-of-the-numbers Easy