Open In App

Arrange given numbers to form the biggest number | Set 1

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: 

// 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
    // 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 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;
}
// 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
                  int comparison = XY.compareTo(YX);
                return comparison == 0 ? 0 : (comparison > 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 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
}
<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>
<?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
?>

Output
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.

// Given an array of numbers,
// program to arrange the numbers
// to form the largest number
import 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 program to arrange the
# given array of numbers
# to form the largest number
import 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 strings
def 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 code
arr = [54, 546, 548, 60]

# Function Hall
printLargest(arr)

# This code is contributed by phasing17
// Given an array of numbers,
// program to arrange the numbers
// to form the largest number
using 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
// 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 strings
function 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 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 phasing17
// 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 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
    // 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 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

Output
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.  

#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
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 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
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--);
        }
    }
}
// JavaScriptimplementation this is to use itertools.
// permutations as coded below:

function largest(l) {
let lst = [];
l.sort(); // sort the array in ascending order
do {
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

Output
6054854654

Time Complexity:  O(n!)
Auxiliary Space: O(1).

This article is compiled by Ravi Chandra Enaganti and improved by prophet1999.

Article Tags :