Largest Number

medium array string greedy sorting

Problem

Given a list of non-negative integers nums, arrange them so they form the largest possible number and return it as a string.

Inputnums = [3, 30, 34, 5, 9]
Output"9534330"
Sort strings under the comparator: a should come before b iff a+b > b+a. Strip a leading "0" if every input is 0.

from functools import cmp_to_key
def largest_number(nums):
    s = [str(x) for x in nums]
    s.sort(key=cmp_to_key(lambda a, b: -1 if a + b > b + a else (1 if a + b < b + a else 0)))
    out = "".join(s)
    return "0" if out[0] == "0" else out
function largestNumber(nums) {
  const s = nums.map(String);
  s.sort((a, b) => (b + a).localeCompare(a + b));
  const out = s.join("");
  return out[0] === "0" ? "0" : out;
}
class Solution {
    public String largestNumber(int[] nums) {
        String[] s = new String[nums.length];
        for (int i = 0; i < nums.length; i++) s[i] = String.valueOf(nums[i]);
        Arrays.sort(s, (a, b) -> (b + a).compareTo(a + b));
        if (s[0].equals("0")) return "0";
        StringBuilder sb = new StringBuilder();
        for (String t : s) sb.append(t);
        return sb.toString();
    }
}
string largestNumber(vector<int>& nums) {
    vector<string> s;
    for (int x : nums) s.push_back(to_string(x));
    sort(s.begin(), s.end(), [](const string& a, const string& b) { return a + b > b + a; });
    if (s[0] == "0") return "0";
    string out;
    for (auto& t : s) out += t;
    return out;
}
Time: O(n log n · L) Space: O(n)