×

C++ Program to find the largest number formed from an array

Given an array, write a program to find the largest number that will be formed from the elements of the array. Arrangement should be done in such a way that all the elements contribute to make the largest number. Also, return the largest formed number in string format because the number can be very large.

For example

Test case 1

N = 5

Arr[] = {5, 9, 30, 3, 34}

Output = 9534330

Explanation

The largest value formed with the arrangement of 9,5,34,3,30.

Test case 2

N = 4

Arr[] = {60, 546, 548, 54}

Output = 6054854654

Explanation

The largest value formed with the arrangement of 60,548,546,54.

Brute-force approach

A simple approach is to sort the array and form a string in order to make a largest number. The array sorted in descending order using bubble sort does not work here.

For example, if we take 548, it is greater than 60 but after sorting 60 comes before.

Similarly, 98 is greater than 9 but after sorting it comes after.

Below is the code implementation.

Code

#include <algorithm>

#include <iostream>

#include <string>

#include <vector>

#include<bits/stdc++.h>

using namespace std;


string number(vector<int>& nums){ // declare a function

  if( nums[0]==0 && nums[nums.size()-1] == 0) // if array contains 0

return "0";

        vector<string> result;

          // push array element to string vector

        for(auto x:nums){

            result.push_back(to_string(x));

        }

          // Sort the result vector

        for(int i=0;i<nums.size()-1;i++){

            for(int j=0;j<nums.size()-i-1;j++){

                if(result[j]+result[j+1]<result[j+1]+result[j]){

                    swap(result[j],result[j+1]);

                }

            }

        }

          // Append it to ans string

        string ans="";

        for(int i=0;i<result.size();i++){

            ans+=result[i];

        }

        return ans; // print ans

}

int main()

{

          vector<int> arr;

          arr.push_back(54);

          arr.push_back(546);

          arr.push_back(548);

          arr.push_back(60);

cout  << number(arr);

          return 0;

}

Output

6054854654

Time complexity

O(n*n)

Space complexity

O(1)

Comparison based sorting

The problem occurred in the brute force approach will be covered in this approach. While sorting the array, we will modify the default compare function according to our needs.

The function my_compare() will work in this way.

This function will compare two numbers X and Y. If the formation of XY is greater then X will come first in the sorting order otherwise Y will come in the sorting order.

For example, if we have x as 541 and Y as 60. We compare 54160 and 60541. The greater one is 60541 so Y remains first.

Code

#include <algorithm>

#include <iostream>

#include <string>

#include <vector>

#include<bits/stdc++.h>

using namespace std;


int my_Compare(int X, int Y)

{

string x1= to_string(X); // x is  convert to string

    string y1 =to_string(Y); // y is  convert to string

         

          string XY = x1.append(y1); // Make combination of XY by append X to Y


          string YX = y1.append(x1); // Make combination of YX by append Y to X

     

          return XY.compare(YX) > 0 ? 1 : 0; // Compare for the greater one

}


void printLargest(vector<int> arr)

{
       

          sort(arr.begin(), arr.end(), my_Compare); // Sort the arr by using my_Compare

          for (int i = 0; i < arr.size(); i++)

                   cout << arr[i]; // Print the array arranged in form of largest number

}

int main()

{

          vector<int> arr; // make a vector

          arr.push_back(54);

          arr.push_back(546);

          arr.push_back(548);

          arr.push_back(60);

          printLargest(arr);

        return 0;

}

Output

6054854654

Time complexity

O(nlogn)

Space complexity

O(n)

Using itertools

If we want to do this problem using Python, a module itertools.combination() is used to find all the combinations of an array.

For example

Input : arr[] = [1, 2, 3, 4],

            r = 2

Output : [[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]]

Here r is the length of a set of sequences that can be formed.

Now this module can be applied to our array. We can find all the possible combinations of the array and make a string of a particular sequence set.

Finally, we will get the largest string.

Code

#import itertools from permutations

from itertools import permutations

def largest(l): # function to print largest number formed

    lst = [] #an array to store the result

    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) # return max of the lst

print(largest([54, 546, 548, 60])) # Call largest function

Output

6054854654

Related Topics

Reverse an Array in C++

The many approaches to reverse an array in the C++ programming language will be discussed in this section. The term "reverse of an array" refers to changing the order of...

8 minutes read.

Memset in C++

Memset () is a function in the C++ programming language that fills memory blocks. The value of "ch" is first converted to an unsigned character. In this case, "ch" denotes the...

3 minutes read.

C++ Mutable keyword

C++ mutable keyword Mutable class storage specifier in C++ Storage class specifiers in C are auto, register, static, and external. Typedef is also considered as a specifier of the storage...

4 minutes read.

Naming Convention in C++

The first and most fundamental step a programmer takes to produce clean code is to name a file or a variable. This naming must be acceptable so that it serves...

5 minutes read.

C++ Program to find the element that occurs once

Write a program to find the element in the array that occurs once. Given that all the numbers in the array are present two times and the array is sorted,...

7 minutes read.

How to declare a 2D array dynamically in C++

In this article, we will learn how to declare the dynamic array in C++. We also learn the initialization of a 2D array using a pointer in C++. Here, we...

3 minutes read.

C++ Math Functions

C++ Math Functions: Like other programming languages, C++ offers plenty of mathematical functions needed for various purposes. These functions are defined mainly in the math library in C++. Let us...

4 minutes read.

Factory Method for Designing Pattern in C++

In C++, the factory method is a type of conditional design pattern. The factory method is related to creating a new object in C++. With the help of a factory...

3 minutes read.

Vector resize() in C++

Vector resize() in C++ Vectors are called dynamic arrays and can automatically adjust their size when a component is added or deleted. This container is used for storage. The function modifies the...

3 minutes read.

CPP Templates

C++ provides a powerful feature called template, which allows the definition of generic classes and generic functions. Generic programming is a technique where different algorithms work in communion by using...

4 minutes read.

C++ Inheritance

What do you mean by Inheritance ? The ability to define new classes based on existing classes in order to reuse and organise code is referred to as inheritance. Single inheritance...

7 minutes read.

Copy constructor

Let's start by learning what a constructor is before diving into the copy constructor in C++. What is a constructor? A constructor is a particular type of class member function that configures the objects of...

7 minutes read.

Hexadecimal to Decimal in C++

In computers, hexadecimal numbers are represented with base 16 and decimal numbers are represented with base 10 and values 0-9, whereas hexadecimal numbers have digits ranging from 0 to 15,...

3 minutes read.

Multiset in C++

Introduction Multisets are part of the C++ STL, or Standard Template Library. In C++, a multiset is a set of associative containers that hold ordered items. Items in a multiset can...

10 minutes read.

C++ find missing in the second array

Given two arrays A and B of sizes n and m. Find the elements from array A that are not present in array B. Example Input : a[] = {1, 2, 3, 5,...

3 minutes read.

C++ Polymorphism

Polymorphism refers to the fact that something exists in several forms. Polymorphism, in simple terms, is the ability of a message to be presented in several formats. A real-life example...

4 minutes read.

Use of Inheritance in C++

What is inheritance in c++? Inheritance is fundamental in object-oriented programming (OOP) languages like C++. It allows a programmer to create a new class (called a derived class) that inherits the...

4 minutes read.

Const_cast in C++ Type Casting Operators

In this tutorial, we will learn enough about const cast in the most widely used programming language, C++, as well as type casting operations. C++ supports the four types of casting...

4 minutes read.

C++ Comments

Comment/Remark A Comment or a Remark is text that is ignored by the compiler yet is beneficial to programmers. Code is usually annotated with comments for future reference. They are treated...

3 minutes read.

Bitmasking in C++

Bitmasking is a technique that is used to access a particular bit within the data bytes. When you apply the iterative approach, this phenomenon is used. A bitmask is described...

6 minutes read.