Arrange given numbers to form the biggest number
Last Updated :
20 Jan, 2025
Given an array of non-negative integers arr[], the task is to arrange them in a manner such that after concatenating them in order, it results in the largest possible number. Since the result may be very large, return it as a string.
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".
Input: arr[] = [3, 4, 6, 5, 9]
Output: "96543"
Explanation: The arrangement [9, 6, 5, 4, 3], gives the largest value "96543".
Using Custom Comparator Sort - O(n*log(n)) Time and O(N) Auxiliary 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
.
Detailed 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++
// C++ program to arrange given numbers to form
// the biggest number using custom comparator sort
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
// Custom comparator to compare concatenated strings
bool myCompare(const string& s1, const 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
// Java program to arrange given numbers to form
// the biggest number using custom comparator sort
import java.util.*;
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
# Python program to arrange given numbers to form
# the biggest number using custom comparator sort
from functools import cmp_to_key
def my_compare(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(my_compare))
# 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#
// C# program to arrange given numbers to form
// the biggest number using custom comparator sort
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
// JavaScript program to arrange given numbers to form
// the biggest number using custom comparator sort
// 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));
Similar Reads
Arrange given numbers to form the biggest number | Set 2 Given an array of non-negative numbers(of Integer Range), they are needed to be arranged in some order such that it gives the max number. For example given array is A[1, 34, 3, 98, 9, 76, 45, 4, 12, 121]. if we arrange these numbers in the following order, A[9, 98, 76, 45, 4, 34, 3, 12, 121, 1], the
3 min read
Arrange given numbers to form the smallest number Given an array arr[] of integer elements, the task is to arrange them in such a way that these numbers form the smallest possible number. For example, if the given array is {5, 6, 2, 9, 21, 1} then the arrangement will be 1212569. Examples: Input: arr[] = {5, 6, 2, 9, 21, 1} Output: 1212569 Input: a
14 min read
Biggest number by arranging numbers in certain order Given an array of n numbers. Arrange them in a way that yields the largest value. While arranging the order of even numbers with respect to each other and the order of odd numbers with respect to each other should be maintained respectively. Examples: Input : {78, 81, 88, 79, 117, 56} Output : 81797
8 min read
Maximum number formed from the digits of given three numbers Given 3 four-digit integers A, B, and C, the task is to print the number formed by taking the maximum digit from all the digits at the same positions in the given numbers. Examples: Input: A = 3521, B = 2452, C = 1352Output: 3552Explanation: The maximum of the digits that are at 1th place is equal t
7 min read
Find maximum number that can be formed using digits of a given number Given a number, write a program to find a maximum number that can be formed using all of the digits of this number.Examples: Input : 38293367Output : 98763332Input : 1203465Output: 6543210Simple Approach: The simple method to solve this problem is to extract and store the digits of the given number
6 min read