Create Largest Concatenated Number
Last Updated :
12 Jul, 2025
Given an array of non-negative integers arr[], arrange them such that their concatenation forms the largest possible number. Return the result as a string, since it may be too large for standard integer types.
Examples:
Input: arr[] = [3, 30, 34, 5, 9]
Output: "9534330"
Explanation: The arrangement [9, 5, 34, 3, 30], gives the largest value "9534330".
Input: arr[] = [54, 546, 548, 60]
Output: "6054854654"
Explanation: The arrangement [60, 548, 546, 54], gives the largest value "6054854654".
[Approach] Using Custom Comparator Sort - O(n*log(n)) Time and O(n) Space
Can we simply sort the numbers in descending order and concatenate them?
No, this approach is incorrect as we are concerned about the order of digits on concatenation of numbers, rather than their numeric values. For example: arr[] = [2, 3, 10], if we sort the array and concatenate the numbers, we will get result as "1032", whereas the correct result is "3210". Since we are concerned about the order or digits and not the numeric value, so first convert the numbers to strings.
Can we simply sort the array of strings in descending order and concatenate them?
No, this approach will fail for test cases where the leading digits are same. For example, arr[] = ["20", "2", "3"], if we sort the strings and concatenate them, we will get "3202" as the maximum number but the actual maximum number is "3220".
The correct approach is to sort the numbers based on the lexicographical ordering of their concatenations. To achieve the correct order, we need to define a custom comparator for sorting. We compare two strings X
and Y
by comparing the concatenated results of XY
and YX
.
Idea to use custom comparison function to sort the array:
- For two strings X and Y, compare the concatenated results XY (X followed by Y) and YX (Y followed by X).
- If XY is greater than YX, then X should come before Y in the final result.
C++
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
// Custom comparator to compare concatenated strings
static bool myCompare(string& s1, string& s2) {
return (s1 + s2) > (s2 + s1);
}
// Function to return the largest concatenated number
string findLargest(vector<int>& arr) {
vector<string> numbers;
for(int ele: arr) {
numbers.push_back(to_string(ele));
}
// Sort the array using the custom comparator
sort(numbers.begin(), numbers.end(), myCompare);
// Handle the case where all numbers are zero.
// We are sorting is descending order, so zero
// in front means complete array contains zero
if (numbers[0] == "0") {
return "0";
}
// Concatenate the sorted array
string res = "";
for (string& num : numbers) {
res.append(num);
}
return res;
}
int main() {
vector<int> arr = { 3, 30, 34, 5, 9 };
cout << findLargest(arr) << endl;
return 0;
}
Java
import java.util.ArrayList;
import java.util.Collections;
class GfG {
// Custom comparator to compare concatenated strings
static boolean myCompare(String s1, String s2) {
return (s1 + s2).compareTo(s2 + s1) > 0;
}
// Function to return the largest concatenated number
static String findLargest(int[] arr) {
// Convert the array of integers to an array of strings
ArrayList<String> numbers = new ArrayList<>();
for (int ele : arr) {
numbers.add(Integer.toString(ele));
}
// Sort the array using the custom comparator
Collections.sort(numbers, (s1, s2) -> myCompare(s1, s2) ? -1 : 1);
// Handle the case where all numbers are zero.
// We are sorting in descending order, so zero
// in front means complete array contains zero
if (numbers.get(0).equals("0")) {
return "0";
}
// Concatenate the sorted array
StringBuilder res = new StringBuilder();
for (String num : numbers) {
res.append(num);
}
return res.toString();
}
public static void main(String[] args) {
int[] arr = { 3, 30, 34, 5, 9 };
System.out.println(findLargest(arr));
}
}
Python3
from functools import cmp_to_key
def myCompare(s1, s2):
if s1 + s2 > s2 + s1:
return -1
else:
return 1
# Function to return the largest concatenated number
def findLargest(arr):
numbers = [str(ele) for ele in arr]
# Sort the array using the custom comparator
numbers.sort(key=cmp_to_key(myCompare))
# Handle the case where all numbers are zero.
# We are sorting in descending order, so zero
# in front means complete array contains zero
if numbers[0] == "0":
return "0"
# Concatenate the sorted array
res = "".join(numbers)
return res
if __name__ == "__main__":
arr = [3, 30, 34, 5, 9]
print(findLargest(arr))
C#
using System;
class GfG {
// Custom comparator to compare concatenated strings
public static bool myCompare(string s1, string s2) {
return (s1 + s2).CompareTo(s2 + s1) > 0;
}
// Function to return the largest concatenated number
public static string findLargest(int[] arr) {
string[] numbers = new string[arr.Length];
for (int i = 0; i < arr.Length; i++) {
numbers[i] = arr[i].ToString();
}
// Sort the array using the custom comparator
Array.Sort(numbers, (s1, s2) => myCompare(s1, s2) ? -1 : 1);
// Handle the case where all numbers are zero.
// We are sorting in descending order, so zero
// in front means complete array contains zero
if (numbers[0] == "0") {
return "0";
}
// Concatenate the sorted array
string res = "";
foreach (string num in numbers) {
res += num;
}
return res;
}
static void Main() {
int[] arr = { 3, 30, 34, 5, 9 };
Console.WriteLine(findLargest(arr));
}
}
JavaScript
// Custom comparator to compare concatenated strings
function myCompare(s1, s2) {
return (s1 + s2) > (s2 + s1);
}
// Function to return the largest concatenated number
function findLargest(arr) {
// Convert the array elements to strings
let numbers = arr.map(String);
// Sort the array using the custom comparator
numbers.sort((s1, s2) => myCompare(s1, s2) ? -1 : 1);
// Handle the case where all numbers are zero.
// We are sorting in descending order, so zero
// in front means the complete array contains zero
if (numbers[0] === "0") {
return "0";
}
// Concatenate the sorted array
return numbers.join('');
}
// Driver Code
let arr = [3, 30, 34, 5, 9];
console.log(findLargest(arr));
Arrange given numbers to form the biggest number
Visit Course
Similar Reads
Nth character in Concatenated Decimal String If all decimal numbers are concatenated in a string then we will get a string that looks like string P as shown below. We need to tell the Nth character of this string. P = â12345678910111213141516171819202122232425262728293031â¦.â Examples: N = 10 10th character is 1 N = 11 11th character is 0 N = 5
9 min read
Add 1 to a given number Write a program to add one to a given number. The use of operators like '+', '-', '*', '/', '++', '--' ...etc are not allowed. Examples: Input: 12 Output: 13 Input: 6 Output: 7 Method: Adding 1 to a given number by importing add function and without using +,- etc. C++ #include <iostream> #incl
7 min read
Check if a number is formed by Concatenation of 1, 14 or 144 only Given a number N . The task is to check if the number is formed by concatenating the numbers 1, 14 and 144 only any number of times and in any order.If it is possible, print YES otherwise print NO.Example: Input: N = 141411 Output: YES Input: N = 14134 Output: NO The idea is to fetch single digit, d
5 min read
JavaScript Number toString() Method The toString() method in JavaScript returns a number as a string. It allows converting numerical values to string representations, enabling operations like formatting output, displaying numbers in various formats, and facilitating string manipulation based on numeric values.Syntax:num.toString(base)
2 min read
Count of digits after concatenation of first N positive integers Given a positive integer N, the task is to find the total number of digits in the concatenation of the first N positive integers.Examples: Input: N = 10 Output: 11 Explanation: The number formed is 12345678910. Hence, the total number of digits = 11Input: N = 20 Output: 31 Explanation: The number fo
4 min read
Find the next number by adding natural numbers in order on alternating indices from last Given a numeric string S of size N, the task is to find the number formed by adding numbers 1, 2, 3, ... up to infinity to every alternative digit of the given numeric string S(starting from the last position). At any point, if the addition result is not a single digit, perform the repeated addition
7 min read