Arrange given numbers to form the biggest number | Set 1 - GeeksforGeeks

28 Apr, 2022
Given an array of numbers, arrange them in a way that yields the largest value. For example, if the given numbers are {54, 546, 548, 60}, the arrangement 6054854654 gives the largest value. And if the given numbers are {1, 34, 3, 98, 9, 76, 45, 4}, then the arrangement 998764543431 gives the largest value.
A simple solution that comes to our mind is to sort all numbers in descending order, but simply sorting doesn’t work. For example, 548 is greater than 60, but in output 60 comes before 548. As a second example, 98 is greater than 9, but 9 comes before 98 in output.
So how do we go about it? The idea is to use any comparison based sorting algorithm. In the used sorting algorithm, instead of using the default comparison, write a comparison function myCompare() and use it to sort numbers.
For Python, the procedure is explained in largestNumber() function.
Given two numbers X and Y, how should myCompare() decide which number to put first – we compare two numbers XY (Y appended at the end of X) and YX (X appended at the end of Y). If XY is larger, then X should come before Y in output, else Y should come before. For example, let X and Y be 542 and 60. To compare X and Y, we compare 54260 and 60542. Since 60542 is greater than 54260, we put Y first.
Following is the implementation of the above approach. To keep the code simple, numbers are considered as strings, the vector is used instead of a normal array. 
Below is the implementation of the above approach: 
C++
Java
Python3
C#
PHP
Javascript
// Given an array of numbers,// program to arrange the numbers// to form the largest number#include <algorithm>#include <iostream>#include <string>#include <vector>using namespace std; // A comparison function which// is used by sort() in// printLargest()int myCompare(string X, string Y){    // first append Y at the end of X    string XY = X.append(Y);     // then append X at the end of Y    string YX = Y.append(X);     // Now see which of the two    // formed numbers is greater    return XY.compare(YX) > 0 ? 1 : 0;} // The main function that prints// the arrangement with the// largest value. The function// accepts a vector of stringsvoid printLargest(vector<string> arr){         // Sort the numbers using    // library sort function. The    // function uses our comparison    // function myCompare() to    // compare two strings. See    // http://www.cplusplus.com/reference/    // algorithm/sort/    // for details    sort(arr.begin(), arr.end(), myCompare);     for (int i = 0; i < arr.size(); i++)        cout << arr[i];} // Driver codeint main(){    vector<string> arr;     // output should be 6054854654    arr.push_back("54");    arr.push_back("546");    arr.push_back("548");    arr.push_back("60");    printLargest(arr);     return 0;}
// Given an array of numbers, program to// arrange the numbers to form the// largest numberimport java.util.*; class GFG {     // The main function that prints the    // arrangement with the largest value.    // The function accepts a vector of strings    static void printLargest(Vector<String> arr)    {         Collections.sort(arr, new Comparator<String>()        {            // A comparison function which is used by            // sort() in printLargest()            @Override public int compare(String X, String Y)            {                 // first append Y at the end of X                String XY = X + Y;                 // then append X at the end of Y                String YX = Y + X;                 // Now see which of the two                // formed numbers                // is greater                return XY.compareTo(YX) > 0 ? -1 : 1;            }        });         Iterator it = arr.iterator();         while (it.hasNext())            System.out.print(it.next());    }     // Driver code    public static void main(String[] args)    {         Vector<String> arr;        arr = new Vector<>();         // output should be 6054854654        arr.add("54");        arr.add("546");        arr.add("548");        arr.add("60");        printLargest(arr);    }}// This code is contributed by Shubham Juneja
def largestNumber(array):    #If there is only one element in the list, the element itself is the largest element.    #Below if condition checks the same.       if len(array)==1:         return str(array[0])    #Below lines are code are used to find the largest element possible.    #First, we convert a list into a string array that is suitable for concatenation    for i in range(len(array)):        array[i]=str(array[i])    # [54,546,548,60]=>['54','546','548','60']    #Second, we find the largest element by swapping technique.    for i in range(len(array)):        for j in range(1+i,len(array)):            if array[j]+array[i]>array[i]+array[j]:                array[i],array[j]=array[j],array[i]    #['60', '548', '546', '54']    #Refer JOIN function in Python    result=''.join(array)    #Edge Case: If all elements are 0, answer must be 0    if(result=='0'*len(result)):        return '0'    else:        return result                  if __name__ == "__main__":    a = [54, 546, 548, 60]    print(largestNumber(a))
// C# program for above approachusing System.Collections.Generic;using System; namespace LargestNumberClass {class LargestNumberClass {    // Given a list of non-negative    // integers,    // arrange them such that they    // form the largest number.    // Note: The result may be very    // large, so you need to    // return a string instead    // of an integer.    public static void    LargestNumberMethod(List<int> inputList)    {        string output = string.Empty;         List<string> newList = inputList.ConvertAll<string>(            delegate(int i) { return i.ToString(); });         newList.Sort(MyCompare);         for (int i = 0; i < inputList.Count; i++)        {            output = output + newList[i];        }         if (output[0] == '0' && output.Length > 1)        {            Console.Write("0");        }        Console.Write(output);    }     internal static int MyCompare(string X, string Y)    {        // first append Y at the end of X        string XY = X + Y;         // then append X at the end of Y        string YX = Y + X;         // Now see which of the two        // formed numbers is greater        return XY.CompareTo(YX) > 0 ? -1 : 1;    }} class Program {       // Driver code    static void Main(string[] args)    {        List<int> inputList            = new List<int>() { 54, 546, 548, 60 };        LargestNumberClass.LargestNumberMethod(inputList);    }}// This code is contributed by Deepak Kumar Singh}
<?php// Given an array of numbers, program// to arrange the numbers to form the// largest number // A comparison function which is used// by sort() in printLargest()function myCompare($X, $Y){    // first append Y at the end of X    $XY = $Y.$X;         // then append X at the end of Y    $YX = $X.$Y;         // Now see which of the two formed    // numbers is greater    return strcmp($XY, $YX) > 0 ? 1: 0;} // The main function that prints the// arrangement with the largest value.// The function accepts a vector of stringsfunction printLargest($arr){    // Sort the numbers using library sort    // function. The function uses our    // comparison function myCompare() to    // compare two strings.    // See http://www.cplusplus.com/reference/    // algorithm/sort/    // for details    usort($arr, "myCompare");     for ($i = 0; $i < count($arr) ; $i++ )        echo $arr[$i];} // Driver Code$arr = array("54", "546", "548", "60");printLargest($arr); // This code is contributed by// rathbhupendra?>
<script>// Given an array of numbers,// program to arrange the numbers// to form the largest number // A comparison function which// is used by sort() function in// printLargest() function myCompare(X, Y){    // // first append Y at the end of X    let XY = X + Y;     // // then append X at the end of Y    let YX = Y + X;     // // Now see which of the two    // // formed numbers is greater    return (YX - XY)} // The main function that prints// the arrangement with the// largest value. The function// accepts a vector of strings function printLargest(arr){         // Sort the numbers using    // inbuilt sort function. The    // function uses our comparison    // function myCompare() to    // compare two strings.    arr.sort(myCompare);    for(let i = 0; i < arr.length; i++)    document.write(arr[i])     // join method creates a string out of the array elements.    document.write(arr.join(""))} // Driver code let arr = []; // output should be 6054854654arr.push("54");arr.push("546");arr.push("548");arr.push("60");printLargest(arr); // This code is contributed by shinjanpatra</script>
6054854654
In the above solution we are allowed strings inputs but in case strings are restricted then also we can solve above problem using long long int to find biggest arrangement. The only limitation is that we can not store numbers greater than 10^18. In case it exceeds that the above solution will be the only option.
C++14
// Given an array of numbers,// program to arrange the numbers// to form the largest number#include <algorithm>#include <iostream>#include <string>#include <vector>using namespace std;typedef long long ll; // A comparison function which// is used by sort() in// printLargest()bool myCompare(ll X,ll Y){    // assign X to XY since XY starts with X first    // assign Y to YX since YX starts with Y first    ll XY=X,YX=Y,revX=0,revY=0;         //reverse X and assign to revX    while(X)    {        revX=revX*10+X%10;        X/=10;    }         //reverse Y and assign to revY    while(Y)    {        revY=revY*10+Y%10;        Y/=10;    }         // first append Y at the end of X    while(revY)    {        XY=XY*10+revY%10;        revY/=10;    }     // then append X at the end of Y    while(revX)    {        YX=YX*10+revX%10;        revX/=10;    }     // Now see which of the two    // formed numbers is greater    return XY>YX;} // The main function that prints// the arrangement with the// largest value. The function// accepts a vector of stringsvoid printLargest(vector<ll> arr){         // Sort the numbers using    // library sort function. The    // function uses our comparison    // function myCompare() to    // compare two strings. See    // http://www.cplusplus.com/reference/    // algorithm/sort/    // for details    sort(arr.begin(), arr.end(), myCompare);     for (int i = 0; i < arr.size(); i++)        cout << arr[i];} // Driver codeint main(){    vector<ll> arr;     // output should be 6054854654    arr.push_back(54);    arr.push_back(546);    arr.push_back(548);    arr.push_back(60);    printLargest(arr);     return 0;}// this code is contributed by prophet1999
6054854654
Time Complexity:  O(n logn) ,sorting is considered to have running time complexity of O(n logn) and the for loop runs in O(n) time.Auxiliary Space: O(1)
Another approach:(using itertools) 
Using the inbuilt library of the Python, itertools library can be used to perform this task.  
Python3
# Python3 implementation this is to use itertools.# permutations as coded below: from itertools import permutationsdef largest(l):    lst = []    for i in permutations(l, len(l)):        # provides all permutations of the list values,        # store them in list to find max        lst.append("".join(map(str,i)))    return max(lst) print(largest([54, 546, 548, 60])) #Output 6054854654 # This code is contributed by Raman Monga
6054854654
Time Complexity:  O(n!)Auxiliary Space: O(1).
This article is compiled by Ravi Chandra Enaganti and improved by prophet1999. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
SaurabhTewary
mongaraman
rathbhupendra
deepak1210
shubham_singh
amit143katiyar
Rajput-Ji
GauravRajput1
mulchandanimanisha5
yshailendra
arjunsodhi7
shinjanpatra
prophet1999
abhivk792
Amazon
MakeMyTrip
Paytm
Zoho
Arrays
Paytm
Zoho
Amazon
MakeMyTrip
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Arrays
Linked List vs Array
Python | Using 2D arrays/lists the right way
Search an element in a sorted and rotated array
Array of Strings in C++ (5 Different Ways to Create)
Queue | Set 1 (Introduction and Array Implementation)
Find the Missing Number
Subset Sum Problem | DP-25
K'th Smallest/Largest Element in Unsorted Array | Set 1
Find Second largest element in an array