Javatpoint Logo
Javatpoint Logo

Construct the Largest Number from the Given Array in Java

The problem is the most famous problem usually asked by top IT companies (like Google, Facebook, Amazon, and Microsoft) in the coding phase interview. In this section, we will create Java programs (different logics) that construct the largest number from a given array.

Example:

Input: {10, 68, 75, 7, 21, 12}

Output: 77568211210

From the above-given array, we can construct the possible largest number 77568211210. Note that it does not matter in which order we are appending numbers together.

Note: There should not be a negative number in the array.

The Solution to the Problem

Simply sort the array in descending order and consider that sorted order as the desired result is not possible because the number may not be the largest number.

First, we will create a custom comparator function for the sorting routine that will compare both pairwise comparisons (i.e. XY and YX) and the greater number will come first in sorted order. Note that here, we need not to compare X and Y together.

Java Program to Construct Largest Number from the Given Array

LargestNumber.java

Output:

 The largest number is: 908775854342160

The complexity of the above program is O(nlogn). Where n is the input size.

Let's see another logic for the same.

In the following Java program, we have converted each array element into a string. Because after appending each number together, we get a large number, so it will be good to covert numbers into strings if the array contains more numbers. After that, we have sorted (descending order) the array. Sorting array in descending order may lead to a problem, where set of numbers with the same leading digits.

For example, consider an array {3, 30, 34, 5, 9}.

When we sort the above array in descending order it constructs 9534303 as the largest number. But it is not the correct answer. The correct answer can be achieved by transposing 33 and 3030.

Therefore, while performing shorting, compare (for each pairwise comparison) the number achieved by concatenating the pair in both orders. Once the array is sorted, we get the desired result as the largest number.

There may exist a situation in which an array may consist of zeros. In this case, return 00, if the most significant number is 00. Else return sorted array as the largest number.

Let's implement the above logic in a Java program.

LargestNumber.java

Output:

The constructed largest number is:908775854342160

For the above solution, the time complexity is O(nlogn) and the space complexity is O(n) because we have used an extra space to store the numbers.


Next TopicJava SHA





Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA