The Wayback Machine - https://web.archive.org/web/20240913135348/https://www.geeksforgeeks.org/given-an-array-of-numbers-arrange-the-numbers-to-form-the-biggest-number/
Open In App

Arrange given numbers to form the biggest number | Set 1

Last Updated : 26 Jun, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given an array of strings arr[] of length n, where every string representing a non-negative integers, the task is to arrange them in a manner such that after concatenating them in order, it results in the largest possible number. Since the result may be very large, return it as a string.

Examples:

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.

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.

Approaches to arrange given numbers to form the biggest number:

[Naive Approach] – Using Simple Descending Sort (Incorrect approach) – O(n log(n)) time and O(1) auxiliary Space

A naive approach is to sort the numbers in descending order and then concatenate them. However, this approach will fail. Let’s look at an example where this approach doesn’t work.

Example: “548” is greater than “60”, but in the largest concatenation, “60” should come before “548”.

[Expected Approach] Using Custom Comparator Sort – O(n log(n)) time and O(1) auxiliary Space

The idea is to achieve the correct order, we need to define a custom comparator for sorting. The idea is to compare two numbers X and Y by comparing the concatenated results of XY and YX.

Detailed idea to use custom comparison function to sort the array.

  • For two strings X and Y, compare the concatenated results XY (X followed by Y) and YX (Y followed by X).
  • If XY is greater than YX, then X should come before Y in the final result.

Code Implementation:

C++
#include <bits/stdc++.h>
using namespace std;

// Custom comparator to compare concatenated strings
bool myCompare(const string& X, const string& Y)
{
    return (X + Y) > (Y + X);
}

// Function to return the largest concatenated number
string largestNumber(const vector<string>& arr)
{
    // Sort the array using the custom comparator
    vector<string> sortedArr = arr;
    sort(sortedArr.begin(), sortedArr.end(), myCompare);

    // Handle the case where all numbers are zero
    if (sortedArr[0] == "0") {
        return "0";
    }

    // Concatenate the sorted array
    string result;
    for (const string& num : sortedArr) {
        result += num;
    }

    return result;
}

int main()
{
    vector<string> arr1 = { "3", "30", "34", "5", "9" };
    cout << largestNumber(arr1)
         << endl; // Output: "9534330"

    vector<string> arr2 = { "54", "546", "548", "60" };
    cout << largestNumber(arr2)
         << endl; // Output: "6054854654"

    return 0;
}
Java
import java.util.Arrays;
import java.util.Comparator;

public class LargestNumber {

    public static String largestNumber(String[] arr)
    {
        // Custom comparator to compare concatenated strings
        Comparator<String> myCompare
            = (X, Y) -> (X + Y).compareTo(Y + X);

        // Sort the array using the custom comparator
        Arrays.sort(arr, myCompare.reversed());

        // Handle the case where all numbers are zero
        if (arr[0].equals("0")) {
            return "0";
        }

        // Concatenate the sorted array
        StringBuilder result = new StringBuilder();
        for (String num : arr) {
            result.append(num);
        }

        return result.toString();
    }

    public static void main(String[] args)
    {
        String[] arr1 = { "3", "30", "34", "5", "9" };
        System.out.println(
            largestNumber(arr1)); // Output: "9534330"

        String[] arr2 = { "54", "546", "548", "60" };
        System.out.println(
            largestNumber(arr2)); // Output: "6054854654"
    }
}
Python3
from functools import cmp_to_key

# Custom comparator function


def myCompare(X, Y):
    # Compare two concatenated results
    if X + Y > Y + X:
        return -1
    else:
        return 1

# Function to return the largest concatenated number


def largestNumber(arr):

    # Sort the array with the custom comparator
    arr.sort(key=cmp_to_key(myCompare))

    # Concatenate the sorted array
    result = ''.join(arr)

    # Handle the case where all numbers are zero
    if result[0] == '0':
        return '0'

    return result


# Example usage
arr1 = ["3", "30", "34", "5", "9"]
print(largestNumber(arr1))  # Output: "9534330"

arr2 = ["54", "546", "548", "60"]
print(largestNumber(arr2))  # Output: "6054854654"
JavaScript
function myCompare(X, Y) {
    // Compare two concatenated results
    if (X + Y > Y + X) {
        return -1;
    } else {
        return 1;
    }
}

function largestNumber(arr) {
    // Sort the array with the custom comparator
    arr.sort(myCompare);

    // Concatenate the sorted array
    let result = '';
    for (let num of arr) {
        result += num;
    }

    // Handle the case where all numbers are zero
    if (result[0] === '0') {
        return '0';
    }

    return result;
}

// Example usage
const arr1 = ["3", "30", "34", "5", "9"];
console.log(largestNumber(arr1));  // Output: "9534330"

const arr2 = ["54", "546", "548", "60"];
console.log(largestNumber(arr2));  // Output: "6054854654"

Output
6054854654

Time Complexity:  O(n log n)
Auxiliary Space: O(1)



Similar Reads

Arrange given numbers to form the biggest number | Set 2
Given an array of non-negative numbers(of Integer Range), they are needed to be arranged in some order such that it gives the max number. For example given array is A[1, 34, 3, 98, 9, 76, 45, 4, 12, 121]. if we arrange these numbers in the following order, A[9, 98, 76, 45, 4, 34, 3, 12, 121, 1], then by joining them we get "99876454343121211" as la
3 min read
Arrange given numbers to form the smallest number
Given an array arr[] of integer elements, the task is to arrange them in such a way that these numbers form the smallest possible number. For example, if the given array is {5, 6, 2, 9, 21, 1} then the arrangement will be 1212569. Examples: Input: arr[] = {5, 6, 2, 9, 21, 1} Output: 1212569 Input: arr[] = {1, 2, 1, 12, 33, 211, 50} Output: 11122112
14 min read
Arrange numbers to form a valid sequence
Given an array arr[] with N distinct numbers and another array arr1[] with N-1 operators (either &lt; or &gt;), the task is to organize the numbers to form a valid sequence which obeys relational operator rules with respect to provided operators. Examples: Input: arr[] = {3, 12, 7, 8, 5}; arr1= {'&lt;', '&gt;', '&gt;', '&lt;'} Output: {3, 12, 8, 5,
6 min read
Number of ways to arrange N numbers which are in a range from 1 to K under given constraints.
Given Four integers N, K, P and Q. The task is to calculate the number of ways to arrange N numbers which are in a range from 1 to K such that the first number is P, the last number is Q and no two adjacent numbers are consecutive. Examples: Input: N = 4, K = 3, P = 2, Q = 3 Output: 3 Explanation: For N=4, K=3, P=2, Q=3, ways are [2, 1, 2, 3], [2,
11 min read
Arrange the numbers in the Array as per given inequalities
Given a list of N distinct integers and a list of N-1 inequality signs, the task is to insert the integers between the inequality signs, such that the final inequality formed always holds true.Note: The order of the inequality signs should not be changed. Examples: Input: Integers: [ 2, 5, 1, 0 ], Signs: [ &lt;, &gt;, &lt; ]Output: 0 &lt; 5 &gt; 1
7 min read
Arrange given numbers in a mathematical expression using operators [+, -, *, /] and parentheses to get value 24
Given an array arr[] consisting of 4 integers each between [1-9], the task is to check whether it is possible to get the number 24 by placing the operators +, -, /, and * between the numbers or grouping them using parenthesis. If it is possible then print "Possible", Otherwise print "Not Possible". Examples: Input: arr[] = {3, 6, 8, 2}Output: Possi
11 min read
Count number of ways to arrange first N numbers
Count number of ways to arrange the first N natural numbers in a line such that the left-most number is always 1 and no two consecutive numbers have an absolute difference greater than 2. Examples: Input: N = 4 Output: 4 The only possible arrangements are (1, 2, 3, 4), (1, 2, 4, 3), (1, 3, 4, 2) and (1, 3, 2, 4). Input: N = 6 Output: 9 Naive approa
13 min read
Calculate Stirling numbers which represents the number of ways to arrange r objects around n different circles
S(r, n), represents the number of ways that we can arrange r objects around indistinguishable circles of length n, and every circle n must have at least one object around it. Examples: Input: r = 9, n = 2Output: 109584Input: r = 6, n = 3Output: 225The special cases are: S(r, 0) = 0, trivial.S(r, 1) represents the circular permutation which is equal
15+ min read
Biggest number by arranging numbers in certain order
Given an array of n numbers. Arrange them in a way that yields the largest value. While arranging the order of even numbers with respect to each other and the order of odd numbers with respect to each other should be maintained respectively. Examples: Input : {78, 81, 88, 79, 117, 56} Output : 8179788856117 The numbers are arranged in the order: 81
8 min read
Number of ways to arrange N items under given constraints
We are given N items which are of total K different colors. Items of the same color are indistinguishable and colors can be numbered from 1 to K and count of items of each color is also given as k1, k2, and so on. Now we need to arrange these items one by one under the constraint that the last item of color i comes before the last item of color (i
10 min read
Arrange first N natural numbers such that absolute difference between all adjacent elements &gt; 1
Given an integer N. The task is to find the permutation of first N natural numbers such that the absolute difference between any two consecutive numbers &gt; 1. If no such permutation is possible then print -1. Examples: Input: N = 5 Output: 5 3 1 4 2 Input: N = 3 Output: -1 Approach: There may be many such arrangements possible but one of the most
6 min read
Arrange numbers 1 to N^2 in a Zig-Zag Matrix in ascending order
Given a positive integer N, the task is to print an N × N zig-zag matrix consisting of numbers from 1 to N2, such that the ZigZag traversal of the matrix yields the number in ascending order.Examples: Input: N = 3 Output: 1 2 4 3 5 7 6 8 9 Explanation: Input: N = 4 Output: 1 2 4 7 3 5 8 11 6 9 12 14 10 13 15 16 Approach: The required matrix can be
7 min read
Arrange the array such that upon performing given operations an increasing order is obtained
Given an array arr[] of size N, the task is to print the arrangement of the array such that upon performing the following operations on this arrangement, increasing order is obtained as the output: Take the first (0th index) element, remove it from the array and print it.If there are still elements left in the array, move the next top element to th
13 min read
Number of ways to arrange a word such that all vowels occur together
Given a word containing vowels and consonants. The task is to find that in how many ways the word can be arranged so that the vowels always come together. Given that the length of the word &lt;10. Examples: Input: str = "geek"Output: 6Ways such that both 'e' comes together are 6 i.e. geek, gkee, kgee, eekg, eegk, keeg Input: str = "corporation"Outp
9 min read
Number of ways to arrange K different objects taking N objects at a time
Given two integers K and N, the task is to count the number of ways to arrange K different objects taking N objects at a time. Each arrangement contains one object at most once. The answer can be very large so return the answer modulo 109 + 7.Note: 1 &lt;= N &lt;= K &lt;= 105. Prerequisites: Factorial of a number, Compute nCr % pExamples: Input : N
11 min read
Number of ways to arrange a word such that no vowels occur together
Given an English word of length at most 20 characters. Calculate the number of ways to arrange the word such that no vowels occur together. Note: If the total number of vowels in the given word is one then the result should be 0. Examples: Input : AllahabadOutput : 7200 Input : geeksforgeeksOutput : 32205600 Input : abcdOutput : 0 Since the word co
13 min read
Number of ways to arrange 2*N persons on the two sides of a table with X and Y persons on opposite sides
Given three integers N, X and Y. The task is to find the number of ways to arrange 2*N persons along two sides of a table with N number of chairs on each side such that X persons are on one side and Y persons are on the opposite side. Note: Both X and Y are less than or equals to N.Examples: Input : N = 5, X = 4, Y = 2 Output : 57600 Explanation :
9 min read
Arrange a binary string to get maximum value within a range of indices
Given a string consisting of only 0's and 1's. Now you are given N non-intersecting ranges L, R ( L &lt;= R), more specifically [L1, R1], [L2, R2], ..., [LN, RN], No two of these intervals overlap — formally, for each valid i, j such that i!=j, either Ri&lt;Lj or Rj&lt;Li. The task is to find a valid permutation that will hold two following conditi
8 min read
Arrange N elements in circular fashion such that all elements are strictly less than sum of adjacent elements
Given an array of N integers, the task is to arrange them in a circular arrangement in such a way that the element is strictly less than the sum of its adjacent elements. In case such an arrangement is not possible, then print -1. Note that there can be multiple ways of arranging the elements such that the condition is satisfied and the task is to
8 min read
Find ways to arrange K green balls among N balls such that exactly i moves is needed to collect all K green balls
Given two integers N and K. There are N balls placed in a row. K of them are green and N - K of them are black. The task is to find the number of ways to arrange N balls such that one will need exactly i ( 1 ? i ? K ) moves to collect all the green balls. In one move, we can collect any group of consecutive green balls. Note that the answer can be
10 min read
Count ways to arrange N distinct objects if all clockwise arrangements are considered the same
Given N distinct objects, the task is to find the number of distinct arrangements of N objects if all clockwise arrangements are considered the same. If A, B, and C are three distinct objects, then arrangements {A, B, C}, {C, A, B}, and {B, C, A} are considered the same as all the arrangements are clockwise to each other. Examples: Input: N = 3Outp
4 min read
Arrange rods to make K side Polygon
Given an array of rods[] of size N and an integer value K (3 &lt;= K &lt;= 6), where rods[i] (1 &lt;= rods[i] &lt;= 108) is the length of the ith rod(1 &lt;= rods.length &lt;= 10), the task is to check if it is possible to arrange all the rods to make a regular polygon of K sides without breaking any rod. Examples: Input: rods[] = {1, 1, 2, 2, 2},
10 min read
Arrange consonants and vowels nodes in a linked list
Given a singly linked list, we need to arrange the consonants and vowel nodes of it in such a way that all the vowel nodes come before the consonants while maintaining the order of their arrival. Examples: Input : a -&gt; b -&gt; c -&gt; e -&gt; d -&gt; o -&gt; x -&gt; i Output : a -&gt; e -&gt; o -&gt; i -&gt; b -&gt; c -&gt; d -&gt; xRecommended
15+ min read
Count ways to arrange integers in circle such that no two adjacent are same
Given 2 integers N and M, find the number of ways to arrange N integers in a circle such that every integer is in the range 0 to M-1, and no two adjacent integers are same. As the answer could be large, find the number, modulo 998244353. Examples: Input: N=3, M=3Output: 6Explanation: There are six ways as follows (0, 1, 2), (0, 2, 1), (1, 0, 2), (1
5 min read
Ways to arrange Balls such that adjacent balls are of different types
There are 'p' balls of type P, 'q' balls of type Q and 'r' balls of type R. Using the balls we want to create a straight line such that no two balls of same type are adjacent.Examples : Input : p = 1, q = 1, r = 0 Output : 2 There are only two arrangements PQ and QP Input : p = 1, q = 1, r = 1 Output : 6 There are only six arrangements PQR, QPR, QR
15+ min read
Ways to arrange N balls of K colors with no adjacent same colors
Given infinite balls of K distinct colors. Count the number of ways to arrange N balls in a line such that no two adjacent balls are of same color. Since the answer may be very large, output the result MOD 1000000007. Examples: Input: N = 2, K = 2Output: 2Explanation: We will denote the colors by 'R' and 'G'. There are two possible ways: "RG" and "
5 min read
Arrange array elements such that last digit of an element is equal to first digit of the next element
Given an array arr[] of integers, the task is to arrange the array elements such that the last digit of an element is equal to first digit of the next element. Examples: Input: arr[] = {123, 321} Output: 123 321 Input: arr[] = {451, 378, 123, 1254} Output: 1254 451 123 378 Naive approach: Find all the permutations of the array elements and then pri
9 min read
The biggest possible circle that can be inscribed in a rectangle
Given a rectangle of length l &amp; breadth b, we have to find the largest circle that can be inscribed in the rectangle. Examples: Input : l = 4, b = 8 Output : 12.56 Input : l = 16 b = 6 Output : 28.26 From the figure, we can see, the biggest circle that could be inscribed in the rectangle will have radius always equal to the half of the shorter
4 min read
Biggest Reuleaux Triangle within a Square which is inscribed within a Circle
Given here is a circle of radius r, which inscribes a square which in turn inscribes a reuleaux triangle. The task is to find the maximum possible area of this reuleaux triangle.Examples: Input: r = 6 Output: 50.7434 Input: r = 11 Output: 170.554 Approach: From the figure, it is very clear that, if the side of the square is a, then a?2 = 2r a = ?2r
4 min read
Area of the biggest ellipse inscribed within a rectangle
Given here is a rectangle of length l &amp; breadth b, the task is to find the area of the biggest ellipse that can be inscribed within it.Examples: Input: l = 5, b = 3 Output: 11.775 Input: 7, b = 4 Output: 21.98 Approach: Let, the length of the major axis of the ellipse = 2x and the length of the minor axis of the ellipse = 2yFrom the diagram, it
4 min read
Article Tags :
Practice Tags :