Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Arrange given numbers to form the biggest number | Set 1

  • Difficulty Level : Medium
  • Last Updated : 19 May, 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++




// 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 strings
void printLargest(vector<string> arr)
{
     
    // Sort the numbers using
    // library sort function. The
    // function uses our comparison
    // function myCompare() to
    // compare two strings. See
    // algorithm/sort/
    // for details
    sort(arr.begin(), arr.end(), myCompare);
 
    for (int i = 0; i < arr.size(); i++)
        cout << arr[i];
}
 
// Driver code
int 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;
}


Java




// Given an array of numbers, program to
// arrange the numbers to form the
// largest number
import 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


Python3




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#




// C# program for above approach
using 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




<?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 strings
function printLargest($arr)
{
    // Sort the numbers using library sort
    // function. The function uses our
    // comparison function myCompare() to
    // compare two strings.
    // 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
?>


Javascript




<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 6054854654
arr.push("54");
arr.push("546");
arr.push("548");
arr.push("60");
printLargest(arr);
 
// This code is contributed by shinjanpatra
</script>


Output

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 strings
void printLargest(vector<ll> arr)
{
     
    // Sort the numbers using
    // library sort function. The
    // function uses our comparison
    // function myCompare() to
    // compare two strings. See
    // algorithm/sort/
    // for details
    sort(arr.begin(), arr.end(), myCompare);
 
    for (int i = 0; i < arr.size(); i++)
        cout << arr[i];
}
 
// Driver code
int 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


Python3




# Python3 implementation of the above approach
 
# 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()
from functools import cmp_to_key
 
def myCompare(X, Y):
 
    # assign X to XY since XY starts with X first
    # assign Y to YX since YX starts with Y first
    XY, YX, revX, revY = X, Y, 0, 0
     
    # reverse X and assign to revX
    while(X):
        revX = revX * 10 + X % 10
        X = (X//10)
     
    # reverse Y and assign to revY
    while(Y):
        revY = revY*10 + Y%10
        Y = (Y//10)
     
    # first append Y at the end of X
    while(revY):
        XY = XY*10 + revY%10
        revY = (revY//10)
 
    # then append X at the end of Y
    while(revX):
        YX = YX*10 + revX%10
        revX = (revX//10)
 
    # 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
def 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
    arr.sort(key = cmp_to_key(myCompare))
 
    for i in range(len(arr)):
        print(arr[i],end="")
 
# Driver code
arr = []
 
# output should be 6054854654
arr.append(54)
arr.append(546)
arr.append(548)
arr.append(60)
printLargest(arr)
 
# This code is contributed by shinjanpatra


Javascript




<script>
 
// JavaScript implementation of the above approach
 
// 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)
{
    // assign X to XY since XY starts with X first
    // assign Y to YX since YX starts with Y first
    let XY=X,YX=Y,revX=0,revY=0;
     
    //reverse X and assign to revX
    while(X)
    {
        revX=revX*10+X%10;
        X = Math.floor(X/10);
    }
     
    //reverse Y and assign to revY
    while(Y)
    {
        revY=revY*10+Y%10;
        Y = Math.floor(Y/10);
    }
     
    // first append Y at the end of X
    while(revY)
    {
        XY=XY*10+revY%10;
        revY = Math.floor(revY/10);
    }
 
    // then append X at the end of Y
    while(revX)
    {
        YX=YX*10+revX%10;
        revX=Math.floor(revX/10);
    }
 
    // 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
    // library sort function. The
    // function uses our comparison
    // function myCompare() to
    // compare two strings. See
    // algorithm/sort/
    // for details
    arr.sort(myCompare);
 
    for (let i = 0; i < arr.length; i++)
        document.write(arr[i]);
}
 
// Driver code
 
let arr = [];
 
// output should be 6054854654
arr.push(54);
arr.push(546);
arr.push(548);
arr.push(60);
printLargest(arr);
 
// This code is contributed by shinjanpatra
 
</script>


Output

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 permutations
def 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


Output

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.


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!