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 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;} |
Java
// 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 |
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 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
<?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.     // 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?> |
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 6054854654arr.push("54");arr.push("546");arr.push("548");arr.push("60");printLargest(arr);Â
// This code is contributed by shinjanpatra</script> |
6054854654
Time Complexity:Â O(n log n)
Auxiliary Space: O(X), Where X is the maximum number of digits in the given numbers.
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()static bool myCompare(int x, int y){Â
    int xy = x, yx = y;Â
    // Count length of x and y    int countx = 0, county = 0;Â
    // Count length of X    while (x > 0) {        countx++;        x /= 10;    }Â
    // Count length of Y    while (y > 0) {        county++;        y /= 10;    }Â
    x = xy;    y = yx;Â
    while (countx--)        yx *= 10;Â
    while (county--)        xy *= 10;Â
    // Append x to y    yx += x;Â
    // Append y to x    xy += y;Â
    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 |
Java
// Given an array of numbers,// program to arrange the numbers// to form the largest numberimport java.util.*;Â
public class GFG{Â
  // The main function that prints  // the arrangement with the  // largest value. The function  // accepts a vector of strings  static void printLargest(ArrayList<Integer> arr)  {Â
    // Sort the numbers using    // library sort function. The    // function uses our comparison    // function myCompare() to    // compare two strings.    Collections.sort(arr, new Comparator<Integer>(){Â
      // A comparison function which      // is used by sort() in      // printLargest()      @Override      public int compare(Integer x, Integer y)      {Â
        int xy = x;        int yx = y;Â
        // Count length of x and y        int countx = 0;        int county = 0;Â
        // Count length of X        while (x > 0) {          countx++;          x /= 10;        }Â
        // Count length of Y        while (y > 0) {          county++;          y /= 10;        }Â
        x = xy;        y = yx;Â
        while (countx > 0)        {          countx--;          yx *= 10;        }Â
        while (county > 0)        {          county--;          xy *= 10;        }Â
        // Append x to y        yx += x;Â
        // Append y to x        xy += y;Â
        return -xy + yx;      }    });Â
    for (int i = 0; i < arr.size(); i++)      System.out.print(arr.get(i));  }Â
  // Driver code  public static void main(String[] args)  {    // Output should be 6054854654    ArrayList<Integer> arr = new ArrayList<>();    arr.add(54);    arr.add(546);    arr.add(548);    arr.add(60);Â
    printLargest(arr);Â
  }}Â
// this code is contributed by phasing17 |
Python3
# Python3 program to arrange the# given array of numbers# to form the largest numberimport functoolsÂ
# A comparison function which# is used by sort() in# printLargest()def myCompare(x, y):Â
    xy = x    yx = yÂ
    # Count length of x and y    countx = 0    county = 0Â
    # Count length of X    while (x > 0):        countx += 1        x //= 10Â
    # Count length of Y    while (y > 0):        county += 1        y //= 10Â
    x = xy    y = yxÂ
    while (countx):        countx -= 1        yx *= 10Â
    while (county):        county -= 1        xy *= 10Â
    # Append x to y    yx += xÂ
    # Append y to x    xy += yÂ
    return 1 if xy > yx else -1Â
# The main function that prints# the arrangement with the# largest value. The function# accepts a vector of stringsdef printLargest(arr):Â
    # Sort the numbers using    # library sort function. The    # function uses our comparison    # function myCompare() to    # compare two strings. SeeÂ
    arr.sort(key=functools.cmp_to_key(myCompare))    arr.reverse()Â
    print("".join(map(str, arr)))Â
# Driver codearr = [54, 546, 548, 60]Â
# Function HallprintLargest(arr)Â
# This code is contributed by phasing17 |
C#
// Given an array of numbers,// program to arrange the numbers// to form the largest numberusing System;using System.Collections.Generic;Â
class myCompare : Comparer<int>{Â
  // A comparison function which  // is used by sort() in  // printLargest()  public override int Compare(int x, int y)  {Â
    int xy = x;    int yx = y;Â
    // Count length of x and y    int countx = 0;    int county = 0;Â
    // Count length of X    while (x > 0) {      countx++;      x /= 10;    }Â
    // Count length of Y    while (y > 0) {      county++;      y /= 10;    }Â
    x = xy;    y = yx;Â
    while (countx > 0) {      countx--;      yx *= 10;    }Â
    while (county > 0) {      county--;      xy *= 10;    }Â
    // Append x to y    yx += x;Â
    // Append y to x    xy += y;Â
    return -xy + yx;  }};Â
public class GFG {Â
  // The main function that prints  // the arrangement with the  // largest value. The function  // accepts a vector of strings  static void printLargest(List<int> arr)  {Â
    // Sort the numbers using    // library sort function. The    // function uses our comparison    // function myCompare() to    // compare two strings.    arr.Sort(new myCompare());Â
    for (int i = 0; i < arr.Count; i++)      Console.Write(arr[i]);  }Â
  // Driver code  public static void Main(string[] args)  {    // Output should be 6054854654    List<int> arr = new List<int>();    arr.Add(54);    arr.Add(546);    arr.Add(548);    arr.Add(60);Â
    printLargest(arr);  }}Â
// This code is contributed by phasing17 |
Javascript
// Given an array of numbers,// JavaScript program to arrange the numbers// to form the largest numberÂ
Â
// A comparison function which// is used by sort() in// printLargest()function myCompare(x, y){Â
    let xy = x;    let yx = y;Â
    // Count length of x and y    let countx = 0;    let county = 0;Â
    // Count length of X    while (x > 0) {        countx++;        x = Math.floor(x / 10);    }Â
    // Count length of Y    while (y > 0) {        county++;        y = Math.floor(y / 10);    }Â
    x = xy;    y = yx;Â
    while (countx--)        yx *= 10;Â
    while (county--)        xy *= 10;Â
    // Append x to y    yx += x;Â
    // Append y to x    xy += y;Â
    return xy < yx;}Â
// 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    arr.sort(myCompare);Â
    for (var i = 0; i < arr.length; i++)        process.stdout.write(arr[i].toString());}Â
// Driver codelet arr = [];Â
// Output should be 6054854654arr.push(54);arr.push(546);arr.push(548);arr.push(60);printLargest(arr);Â
// this code is contributed by phasing17 |
6054854654
Time Complexity:Â O(n logn) , sorting is considered to have a 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 Python, itertools library can be used to perform this task. Â
C++
#include <iostream>// C++ implementation this is to use itertools.// permutations as coded below:Â
#include <algorithm>#include <string>#include <vector>Â
using namespace std;Â
string largest(vector<int> l){    vector<string> lst;    sort(l.begin(),         l.end()); // sort the vector in ascending order    do {        string s = "";        for (int i = 0; i < l.size(); i++) {            s += to_string(                l[i]); // convert the integer to a string        }        lst.push_back(s);    } while (next_permutation(        l.begin(),        l.end())); // get the next permutation of the vectorÂ
    return *max_element(lst.begin(), lst.end());}Â
int main(){Â Â Â Â vector<int> v = { 54, 546, 548, 60 };Â Â Â Â cout << largest(v) << endl; // Output: 6054854654Â
    return 0;}Â
// This code is contributed by rutikbhosale |
Java
import java.util.*;Â
class GFG {  static String largest(ArrayList<Integer> l)  {    ArrayList<String> lst = new ArrayList<String>();    Collections.sort(      l); // sort the array list in ascending order    do {      String s = "";      for (int i = 0; i < l.size(); i++) {        s += Integer.toString(l.get(          i)); // convert the integer to a string      }      lst.add(s);    } while (      nextPermutation(l)); // get the next permutation    // of the array listÂ
    return Collections.max(lst);  }Â
  static boolean nextPermutation(ArrayList<Integer> nums)  {    int i = nums.size() - 2;    while (i >= 0 && nums.get(i) >= nums.get(i + 1)) {      i--;    }    if (i < 0) {      return false;    }Â
    int j = nums.size() - 1;    while (nums.get(j) <= nums.get(i)) {      j--;    }Â
    Collections.swap(nums, i, j);    Collections.reverse(      nums.subList(i + 1, nums.size()));    return true;  }Â
  public static void main(String[] args)  {    ArrayList<Integer> v = new ArrayList<Integer>(      Arrays.asList(54, 546, 548, 60));    System.out.println(      largest(v)); // Output: 6054854654  }} |
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 |
Javascript
// JavaScriptimplementation this is to use itertools.// permutations as coded below:Â
function largest(l) {let lst = [];l.sort(); // sort the array in ascending orderdo {let s = "";for (let i = 0; i < l.length; i++) {s += l[i].toString(); // convert the integer to a string}lst.push(s);} while (nextPermutation(l)); // get the next permutation of the arrayÂ
return Math.max(...lst); // find the maximum element in the array}Â
function nextPermutation(arr) {let i = arr.length - 2;while (i >= 0 && arr[i] >= arr[i + 1]) {i--;}Â
if (i < 0) {return false; }Â
let j = arr.length - 1;while (arr[j] <= arr[i]) {j--;}Â
[arr[i], arr[j]] = [arr[j], arr[i]];Â
let left = i + 1;let right = arr.length - 1;Â
while (left < right) {[arr[left], arr[right]] = [arr[right], arr[left]]; left++;right--;}Â
return true; }Â
let v = [54, 546, 548, 60];console.log(largest(v)); // Output: 6054854654// This code is contributed by rutikbhosale |
C#
using System;using System.Collections.Generic;using System.Linq;Â
class GFG{    static string Largest(List<int> l)    {        var lst = new List<string>();        l.Sort(); // sort the list in ascending order        do        {            var s = string.Join("", l.Select(i => i.ToString())); // convert the integers to a string            lst.Add(s);        } while (NextPermutation(l)); // get the next permutation of the listÂ
        return lst.Max();    }Â
    static bool NextPermutation(List<int> nums)    {        int i = nums.Count - 2;        while (i >= 0 && nums[i] >= nums[i + 1])        {            i--;        }        if (i < 0)        {            return false;        }Â
        int j = nums.Count - 1;        while (nums[j] <= nums[i])        {            j--;        }Â
        nums.Swap(i, j);        nums.Reverse(i + 1, nums.Count - (i + 1));        return true;    }Â
    public static void Main(string[] args)    {        var v = new List<int>() { 54, 546, 548, 60 };        Console.WriteLine(Largest(v)); // Output: 6054854654    }}Â
public static class Extensions{Â Â Â Â public static void Swap<T>(this IList<T> list, int i, int j)Â Â Â Â {Â Â Â Â Â Â Â Â T temp = list[i];Â Â Â Â Â Â Â Â list[i] = list[j];Â Â Â Â Â Â Â Â list[j] = temp;Â Â Â Â }Â
    public static void Reverse<T>(this IList<T> list, int index, int count)    {        int i = index, j = index + count - 1;        while (i < j)        {            list.Swap(i++, j--);        }    }} |
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.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!
