Largest Number formed from an Array | Practice | GeeksforGeeks

Given a list of non negative integers, arrange them in such a manner that they form the largest number possible.The result is going to be very large, hence return the result in the form of a string.

Example 1:
Input: 
N = 5
Arr[] = {3, 30, 34, 5, 9}
Output: 9534330
Explanation: Given numbers are {3, 30, 34,
5, 9}, the arrangement 9534330 gives the
largest value.
Example 2:
Input: 
N = 4
Arr[] = {54, 546, 548, 60}
Output: 6054854654
Explanation: Given numbers are {54, 546,
548, 60}, the arrangement 6054854654 
gives the largest value.

Your Task:  
You don't need to read input or print anything. Your task is to complete the function printLargest() which takes the array of strings arr[] as parameter and returns a string denoting the answer.

Expected Time Complexity: O(NlogN)
Expected Auxiliary Space: O(1)

Constraints:
1 ≤ N ≤ 105
0 ≤ Arr[i] ≤ 1018
Sum of all the elements of the array is greater than 0.
+1
satviktiwari13 hours ago
C++: O(nlogn)
 
static bool comp(string s1, string s2){    string x = s1+s2;    string y = s2+s1;    return x>y;}string printLargest(vector<string> &arr) {    sort(arr.begin(), arr.end(), comp);    string ans = "";    for(int i = 0; i < arr.size(); i++){        for(int j = 0; j < arr[i].size(); j++){            ans += arr[i][j];        }    }    return ans;}
0
ritikmishra2 weeks ago
CPP Solution
 
string printLargest(vector<string> &arr) {    sort(arr.begin(),arr.end(),[](string X, string Y){        string XY = X.append(Y);            string YX = Y.append(X);            return XY.compare(YX) > 0 ? 1: 0;    });    string ans="";            for (auto i:arr) ans += i;   // cout << i << " ";    return ans;}
0
danca2262 weeks ago
is the runtime correct? O(n lg n) is the number of comparisons, but each compare is concatenating 2 strings and compare them which takes O(a+b) so it should be O(M*N lg N) where M is the max length of any two strings?
0
manjeetdhaterwal3 weeks ago
java sol
String printLargest(String[] arr) {
        Arrays.sort(arr, (s1, s2)-> 
        {return (s2+s1).compareTo(s1+s2);});
        String s="";
        for(String x:arr) s+=x;
        return s;
    }
0
geek_deepx3 weeks ago
class Solution{
public:

/*
for more reference go to - https://www.cplusplus.com/reference/algorithm/sort/
Beautiful explanation given for the uses of sort() function with our own condition
*/
bool static myCompare(string i, string j){
    string ij = i.append(j);
    string ji = j.append(i);
    return ij.compare(ji) > 0 ? true : false;
}

string printLargest(vector<string> &arr) {
    int n = arr.size();
    string ans;
    sort(arr.begin(), arr.end(), myCompare);
    for(int i = 0; i < n ; i++){
        ans.append(arr[i]);
    }
    return ans;
}
};
0
tushantverma3 weeks ago
Why it's showing error for this code?
class Solution
{
    public String printLargest(String[] arr)
    {
        String k="";
        String s=arr[0];
        for (int i = 0; i < arr.length-1; i++)
        {
           String a= (s.concat(arr[i+1]));
           String b=(arr[i+1].concat(s));
           if(a.compareTo(b)>=0)
           {
               k=(a);
           }
           else
           {
            k=(b);
           }
           s=k;
        }
        return k;
    }
}

0
pavansunny5671 month ago
Python Solution
def printLargest(self,arr):
	    # code here
	    
	    def comp(a,b):
	        s1=a+b
	        s2=b+a
	        if s1<s2:
	            return 1
	        return -1
#         
	    arr.sort(key=functools.cmp_to_key(comp))
	    ans="".join(arr)
	    return ans

0
amishasahu3281 month ago
class Solution{
public:
	// The main function that returns the arrangement with the largest value as
	// string.
	// The function accepts a vector of strings
	static int myCompare(string X, string Y)
	{
	    string XY = X.append(Y);
	    string YX = Y.append(X);
	    return (XY > YX);
	}
	string printLargest(vector<string> &arr) {
	    // code here
	    sort(arr.begin(), arr.end(), myCompare);
	    string ans;
	    for(int i = 0; i < arr.size(); i++)
	        ans.append(arr[i]);
	        
	    return ans;
	}
};
+1
subashig191 month ago
#include<stdio.h>#include<conio.h>#include<string.h>#include<stdlib.h>
int concat(int a,int b);int main(){   //Arr[] = {3, 30, 34, 5, 9}   int arr[]={3, 30, 34, 5, 9};   int length;   length=5;   int i,j;   for(i=0;i<length;i++)   {       for(j=i+1;j<length;j++)       {           int temp;           int v,w;           v=concat(arr[i],arr[j]);           w=concat(arr[j],arr[i]);           if (v>w)           {               ;           }           else           {               temp=arr[i];               arr[i]=arr[j];               arr[j]=temp;           }      }   }   for(i=0;i<length;i++)   {       printf("%d",arr[i]);   }}    int concat(int a,int b){   char s1[20];   char s2[20];   // Convert both the integers to string   sprintf(s1, "%d", a);   sprintf(s2, "%d", b);   // Concatenate both strings   strcat(s1, s2);   // Convert the concatenated string   // to integer   int c = atoi(s1);   // return the formed integer   return c;}
   
0
lindan1232 months ago
	static bool comp(string a,string b)
	{
	    string s1 = a+b;
	    string s2 = b+a;
	    return s1>s2;
	}
	string printLargest(vector<string> &arr) {
	    sort(arr.begin(),arr.end(),comp);
	    int n = arr.size();
	    string str="";
	    for(int i=0;i<n;i++)
	    {
	        str+=arr[i];
	    }
	    return str;
	}
Time Taken : 0.8sec
Cpp
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.