Algo-Sim › Sorting & Divide and Conquer

Largest Number

Medium · Sorting & Divide and Conquer · step through it in Java, Python and C++ on your own input

Arrange numbers to form the largest concatenation: sort strings with the comparator a + b vs b + a, and return "0" when all are zero.

Problem

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

Constraints

Edge cases to test

Follow-up questions

Why is the comparator a valid ordering?
Comparing a + b with b + a is transitive (it compares a and b as repeating decimals), so sorting with it is consistent.
What is the cost?
O(n log n) comparisons, each O(len), so O(n log n · L) for numbers of up to L digits.

Solution

Java

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]);
    // a goes first when a + b is the bigger concatenation.
    Arrays.sort(s, (a, b) -> (b + a).compareTo(a + b));
    if (s[0].equals("0")) return "0";
    return String.join("", s);
}

Python

from functools import cmp_to_key


def largest_number(nums):
    s = [str(x) for x in nums]
    # a goes first when a + b is the bigger concatenation.
    s.sort(key=cmp_to_key(lambda a, b: (b + a > a + b) - (b + a < a + b)))
    if s[0] == "0":
        return "0"
    return "".join(s)

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    string largestNumber(vector<int> &nums) {
        vector<string> s;
        for (int x : nums) s.push_back(to_string(x));
        // a goes first when a + b is the bigger concatenation.
        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 (const string &x : s) out += x;
        return out;
    }
};

More Sorting & Divide and Conquer problems