Practice › Greedy
Largest Number from an Array
Medium · Greedy · Asked at Amazon, Microsoft, Google, Paytm, MakeMyTrip
Arrange the non-negative integers so that, written one after another, they form the largest possible number. Print that number (without leading zeros — if it is zero, print 0).
Input
First line: n. Second line: n space-separated integers.
Output
The largest number.
Constraints
- 1 ≤ n ≤ 10^4
- 0 ≤ a[i] ≤ 10^9
Sort the numbers as strings with the rule "x comes before y if x + y > y + x" (for example 9 before 34, and 3 before 30 because 330 > 303). Join them; if the first one is 0, everything is 0.
Example 1
Input
2 10 2
Output
210
Example 2
Input
5 3 30 34 5 9
Output
9534330
Hints
- Sorting by numeric value does not work: 9 should come before 34 even though it is smaller.
- Compare two numbers by the two ways of joining them: x + y versus y + x (as strings).
- If the biggest piece is "0", the whole answer is 0.
Approach
Convert to strings and sort with the comparator "x before y if x + y > y + x". This order is consistent (it is transitive), and in it no swap of neighbours can make the result larger, so joining the sorted strings gives the largest number. Handle all zeros: the result would be "000…", so print "0" when the first string is "0".
Complexity: O(n log n · d) time, d = digits per number · O(n · d) space
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
cin >> n;
vector<string> a(n);
for (auto &s : a) cin >> s;
sort(a.begin(), a.end(), [](const string &x, const string &y) { return x + y > y + x; });
if (a[0] == "0") {
cout << "0\n";
return 0;
}
string res;
for (auto &s : a) res += s;
cout << res << "\n";
return 0;
}Python solution
import sys
from functools import cmp_to_key
data = sys.stdin.read().split()
n = int(data[0])
a = data[1 : 1 + n]
a.sort(key=cmp_to_key(lambda x, y: -1 if x + y > y + x else (1 if x + y < y + x else 0)))
print("0" if a[0] == "0" else "".join(a))Java solution
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine().trim());
String[] a = br.readLine().trim().split("\\s+");
Arrays.sort(a, (x, y) -> (y + x).compareTo(x + y));
if (a[0].equals("0")) {
System.out.println("0");
return;
}
StringBuilder sb = new StringBuilder();
for (String s : a) sb.append(s);
System.out.println(sb);
}
}Solve Largest Number from an Array online · All practice problems