×

Find next greater number with same set of digits in Java

It contains a number (num). Finding the smallest number that has the same number of elements as num that is also larger than num is the task at hand. If num is the biggest number that can be formed using its digits, then it is impossible to find a bigger number, and a warning should be printed as a result.

Example

For input 89321 the expected output would be 91238

The following numbers are higher than the number 89123 and are composed of the numerals 1, 2, 3, 8, and 9.

98123, 98132, 98213, 98231, 98312, 98321, 93128, 93182, 93218, 93281, 93812, 93821, 92138, 92183, 92318, 92381, 92813, 92831, 91238, 91283, 91328, 91382, 91823, 91832

The least number among all of these is 91238.

Example

For input 3648 the expected output would be 3684

Numbers that are greater than 3648 and comprise the numbers 3, 8, 4, and 6 are:

3684, 4368, 4386, 4638, 4683, 4836, 4863, 6348, 6384, 6438, 6483, 6834, 6843, 8346, 8364, 8436, 8463, 8634, 8643

The least number among all of these is 3684.

Example

For input 9100 The next larger number cannot be determined.

The greatest number that can be constructed with the numbers 9, 1, 0, and 0 is 9100. Therefore, using the provided digits, it is impossible to find a value bigger than 9100.

Observation

Some of the crucial things to notice are listed below.

  • The conclusion is "It is just not possible to identify the next larger number" if a number's digits are arranged in descending order. 98675 is an illustration.
  • When a number's digits are arranged in ascending order, the last two numbers of the number must be switched. For instance, 4576 is the next higher number after 4567.
  • The other circumstances require starting the number processing from the rightmost edge since the smaller of the integers that are greater than the specified number must be found.

Algorithm

The procedure for calculating the next larger integer based on the observation mentioned above is as follows.

Step 1: Starting with the rightmost digit, traverse the integer num until you locate a digit that is smaller than the last digit you travelled. For instance, if the input number is "4975," one must halt at 4. Because 4 is smaller than the digit after it, 9, this occurs. Finding the next larger integer is impossible if such a digit is not obtained.

Step 2: Next, start looking again for smallest digit that is larger than the found digit "d" on its right side. The right-hand side of 4 has a value of 975 for the number 4975. The smallest number larger than four among the numbers 9, 7, and 5 is 5.

Step 3: Next, reverse the order of 4 and 5. One will so receive 5974. But among the largest, this amount is not the smallest. As a result, the numbers after digit 5 must be sorted. Thus, one can obtain 5479 by arranging all digits of the integer 5974. The number 5479, which consists of the digits 4, 9, 7, and 5, is the lowest among those bigger than 4975.

The formula for determining the next larger integer is given below.

  • Starting with the rightmost digit, explore the given number until you locate a digit that is lower than the one you have just visited. In the case of the input number "534976," for instance, we terminate at 4 because it is smaller than the subsequent digit (9). If we are unable to locate one such digit, the outcome will read "Not Possible."
  • Now look for the lowest digit greater than "d" on the right side of the found digit "d" above. The right-hand side of 4 includes "976" for "534976". The smallest number higher than four is six.
  • In the case above, if we swap the two digits we found above, we get 536974.
  • From the point adjacent to the letter "d" until the last digit, sort the numbers now. The output is the number we obtain after sorting. We sorted the numbers in bold 536974 for the example above. The result for input 534976 is "536479," which is the next higher number.

Using Permutation

It is a forceful strategy. Using the digits present in the supplied number num, we shall compute each number that can be created. These calculated numbers will be kept in a hash set, or hs. We shall choose a number from that hash set that is both less than and greater than the integer num.

Nextgrtnum.java

// importing all the requried packages 
import java.util.ArrayList;  
import java.util.HashSet;  
import java.util.Set;  
  
public class Nextgrtnum  
{  
public Set hash;  
// default constructor to the Nextgrtnum class  
Nextgrtnum()  
{  
hash = new HashSet();  
}  
// This method will help in finding the next greater number  
int nextgrt(int val)  
{  
int num = val;      
ArrayList arr = new ArrayList();  
// Using while loop to find the digits in the number with name val'
// and adding those digits to the array list in the reverse order 
while(num != 0)  
{  
arr.add(num % 10);  
num = num / 10;  
}  
  
// using permute method to permutate over all the 
// integers in the arraylist and passing the size of permutation.  
permute(arr, 0, arr.size() - 1);  
  
int answer = Min(hash, val);  
  
return answer;  
}  
  
// This method will find the next mini value 
// from the permute and returns the mini value with those set of digits
public int Min(Set s, int val)  
{  
int mini = Integer.MAX_VALUE;  
  
  
// from the set of integers s we are makking the array 
Integer[] arr = s.toArray(new Integer[s.size()]);  
  
  
// Finding the size of the array arr 
int len = arr.length;  
  
// taking a boolean variable f to indicate that the min is 
// found this will be true when the min is found.
boolean f = false;  
  
for(int i = 0 ; i < len; i++)  
{  
int t = arr[i];  
  
// the number should be greater than the original number 
// so this condition checks the greater number.  
if(t > val)  
{  
//  our goal is to find the min value
// of all the greater number from the same set of digits. 
if(mini > t)  
{  
mini = t;  
  
// as our min value is found we will 
// update our boolean value f to true.  
f = true;  
}  
}  
  
}  
  
  
// we will return the min value only if 
// the min val is found 
if(f)  
{  
return mini;  
}  
// If the control gets to this point,
// the mini value was not located. 
// therefore please return -1. 
return -1;  
}  
  
  
// Swap the value at positions x and y
// in the array list arr. 
public void change(ArrayList arr, int x, int y)  
{  
int i = arr.get(x);  
int j = arr.get(y);  
  
arr.set(x, j);  
arr.set(y, i);  
}  
  
// Create a number using the digits from the 
// array collection. Keep in mind that the order
// of the numbers in the val matches that of the array list.
// For instance, if arr = [2, 3, 6, 1, 1, 9, 8], 
// then 2361198 will be the result. 
int make(ArrayList arr)  
{  
int len = arr.size();  
int num = 0;  
  
for(int i = 0; i < len; i++)  
{  
num = num * 10;  
num = num + arr.get(i);  
}  
  
return num;  
  
}  
  
  
// a technique that uses the digits with in array list 
//arr to determine the possible numbers  
private void permute(ArrayList arr, int l, int r)  
{  
// this is a corner case   
if (l == r)  
{  
// Create the number that use the array list's digits,
// then add the result to the hash set.  
int val = make(arr);  
hash.add(val);  
}  
  
else  
{  
for (int j = l; j <= r; j++)  
{  
// Apply recursion, then alter once more to go backwards.  
change(arr, l, j);  
permute(arr, l + 1, r);  
change(arr, l, j);  
}  
}  
}  
  
  
// main method starts here   
public static void main(String[] argvs)  
{  
// object creation for the class Nextgrtnum  
Nextgrtnum nxtgrtnum = new Nextgrtnum();  
  
// Example 1  
int val = 536479;  
  
int answer = nxtgrtnum.nextgrt(val);  
  
System.out.println("The given in put is: " + val);  
  
if(answer != -1)  
{  
System.out.println("The following is the next higher number is: " + answer);  
}  
else  
{  
System.out.println("The next higher number is not feasible.");      
}  
  
System.out.println();  
  
nxtgrtnum.hash.clear();  
  
// Exampel 2  
val = 654321;  
  
answer = nxtgrtnum.nextgrt(val);  
  
System.out.println("The given in put is: " + val);  
  
if(answer != -1)  
{  
System.out.println("The following is the next higher number is: " + answer);  
}  
else  
{  
System.out.println("The next higher number is not feasible.");      
}  
  
  
System.out.println();  
  
nxtgrtnum.hash.clear();  
  
// input 3  
val = 4876;  
  
answer = nxtgrtnum.nextgrt(val);  
  
System.out.println("The given in put is: " + val);  
  
if(answer != -1)  
{  
System.out.println("The following is the next higher number is: " + answer);  
}  
else  
{  
System.out.println("The next higher number is not feasible.");      
}  
}  
}  

Output:

The given in put is: 536479
The following is the next higher number is: 536497


The given in put is: 654321
The next higher number is not feasible.


The given in put is: 4876
The following is the next higher number is: 6478

Complexity analysis: To discover the next larger number in the aforementioned programme, we used backtracking. As a result, the programme mentioned above has exponential time complexity. Let's say that num has d integers. The total amount of numbers in the hash set is therefore hs n!. As a result, the programme described above has an O(n!) space complexity.

Using the sorting method

Nextgrtnum1.java

// importing all the requried packages  
import java.util.ArrayList;  
import java.util.Collections;  
  
public class Nextgrtnum1  
{  
boolean changepss(ArrayList arrlis)  
{  
int len = arrlis.size();  
int j;  
  
// travesing the loop from right to left using the for loop  
for (j = len - 1; j > 0; j--)  
{  
int xel = arrlis.get(j);  
int yele = arrlis.get(j - 1);  
  
  
if (xel > yele)   
{  
// The processing begins here because we
// have a digit that is smaller than the next digit.  
break;  
}  
}  
  
  
if(j == 0)  
{  
// The numbers' digits are organised in descending order.
// As a result, the next higher number is impossible. 
return false;  
}  
  
int te = arrlis.get(j - 1);  
int least = j;  
  
// locating a digit that exceeds the digit at
// the (j - 1)th index. However, we must choose 
// the least number from the group of larger ones. 
for (int k = j + 1; k < len; k++)  
{  
if (arrlis.get(k) > te && arrlis.get(k) < arrlis.get(least))  
{  
least = k;  
}  
}  
  
// switching to obtain the higher number  
int xel = arrlis.get(j - 1);  
int yele = arrlis.get(least);  
arrlis.set(least, xel);  
arrlis.set(j - 1, yele);  
  
  
// Sorting the greater than num integers 
// to get the one that is the smallest 
Collections.sort(arrlis.subList(j, len));  
  
return true;  
  
}  
  
// a technique that locates the following larger number  
int Nextgrt(int num)  
{  
  
int val = num;      
ArrayList arrlis = new ArrayList();  
  
// loop for removing the digits from 
// the number num & adding them in the opposite
// order to the array list  
while(val != 0)  
{  
arrlis.add(val % 10);  
val = val / 10;  
}  
  
// changing the numbers' order while preserving the existing arrangement  
Collections.reverse(arrlis);  
  
// If the exchange is possible, 
// give the following larger number.  
if(changepss(arrlis))  
{  
int nextnum = 0;  
int len = arrlis.size();  
  
// creating a new number using a loop that
// combines the digits in the list to produce 
// the next larger number  
for (int j = 0; j < len; j++)  
{  
nextnum = nextnum * 10;  
nextnum = nextnum + arrlis.get(j);  
}  
  
// giving back the updated larger number 
return nextnum;  
}  
  
  
  
// if the control reaches here, then it means the next greater number is not   
// possible. Hence, -1 is returned  
return -1;  
}  
  
  
// main method starts here    
public static void main(String[] argvs)  
{  
// object creation for the class Nextgrtnum1  
Nextgrtnum1 Nextgrtnum1 = new Nextgrtnum1();  
  
// Example 1  
int num = 536479;  
  
int ans = Nextgrtnum1.Nextgrt(num);  
  
System.out.println("The given in put is: " + num);  
  
if(ans != -1)  
{  
System.out.println("The following is the next higher number is: " + ans);  
}  
else  
{  
System.out.println("The next higher number is not feasible.");      
}  
  
System.out.println();  
  
// Example 2  
num = 654321;  
  
ans = Nextgrtnum1.Nextgrt(num);  
  
System.out.println("The given in put is: " + num);  
  
if(ans != -1)  
{  
System.out.println("The following is the next higher number is:  " + ans);  
}  
else  
{  
System.out.println("The next higher number is not feasible.");      
}  
  
  
System.out.println();  
  
  
// Example 3  
num = 4876;  
  
ans = Nextgrtnum1.Nextgrt(num);  
  
System.out.println("The given in put is: " + num);  
  
if(ans != -1)  
{  
System.out.println("The following is the next higher number is: " + ans);  
}  
else  
{  
System.out.println("The next higher number is not feasible.");      
}  
}  
}  

Output:

The given in put is: 536479
The following is the next higher number is: 536497


The given in put is: 654321
The next higher number is not feasible.


The given in put is: 4876
The following is the next higher number is: 6478

Related Topics

Java Clone Array

We frequently need to copy an array to back up its original components. We have a few unique numbers and strings, including Armstrong numbers, palindrome numbers, and palindrome strings. To...

4 minutes read.

How to Convert char to String in Java

How to Convert char to String in Java There are two methods to convert char to String: Using String.valueOf(char) method Using Charcter.toString(char) method Using String.valueOf(char) method valueOf(char) is the static method of String class that...

2 minutes read.

Program to find and replace characters on string in java

In JAVA, Strings are immutable. To overcome this Java String class contains a lot of methods to do operations on Strings. One such method is replace method. String Replace It returns a...

3 minutes read.

Iterate JSON array in Java

This article is going to equip the knowledge about what JSON array is and how it works and also how is it distinct with the generic array. Json Array Ordered lists of...

4 minutes read.

Java Coding Software

Desktop and web apps are created using Java, an object-oriented programming language. Java code may be executed on any platform, making it platform-independent. A text editor, tool, or piece of...

9 minutes read.

Java String getBytes() method

getBytes() method returns sequence of bytes. Syntax: There are three variants of getBytes() method: public byte[] getBytes()        public byte[] getBytes(String charsetName) public byte[] getBytes(Charset charset) Returns: It returns sequence of bytes. Java String getBytes() Example...

2 minutes read.

Java Math exp() Method

The exp() method of Math class returns Euler’s number(e) raised to the power of a double value. Syntax: public static double exp(double a) Parameters: The parameter ‘a’ represents the exponent e. Return Value: The exp ()...

2 minutes read.

Java RandomAccessfile

Writing and reading to random access files are done using this class. An array of many bytes is how a random access file operates. By changing the implied file pointer...

3 minutes read.

Internal Working of ArrayList in Java

Java's version of a resizable array is called ArrayList. The dynamic growth of an array list ensures that there is always room for new elements. ArrayList's backing data structure is...

8 minutes read.

Zigzag Traversal of Binary Tree in Java

In this article, you will be acknowledged about the zigzag traversal of binary tree in java and the approaches or ways in which the zigzag traversal can be done. Zigzag Traversal A...

10 minutes read.

Java InputStreamReader

What is InputStreamReader?An InputStreamReader is a converter between byte and character streams: It reads bytes and converts them to characters with the help of a charset. The charset it uses can...

4 minutes read.

Normal and Trace of a Matrix in Java

Normal of a matrix The square root of the total squares of each element in a matrix is known as the matrix's normal. Think of the following matrix as an example. Example: [[1,2,3]  ...

3 minutes read.

Replace character in string Java

Characters in Java In the package of Java language, there is a container class called Character. A single field of type char is contained in a Character object. For manipulating characters,...

4 minutes read.

Abstract classes in Java

Abstract classes in Java Java uses the 'abstract’ keyword to make a class abstract. Such classes are known as abstract classes, and the process is known as abstraction. In programming language, abstract...

4 minutes read.

Java HashSet

HashSet implements the set interface. It uses the hash table to make the collection to store different data types. The hash set is the unordered collection of different data types....

6 minutes read.

Java Base64 Encoding and Decoding

Introduction to Encoding and Decoding Encoding is the process of putting the sequence of characters like letters, numbers, punctuations, and other symbols into a specialised format for the efficient transmission or...

11 minutes read.

How to open the Java control panel

The many methods for launching the Java control panel will be covered in this section. We will also go through how the Java Control Panel can be used. Java Control Panel The...

2 minutes read.

How to Split the String in Java with Delimiter

In Java, splitting strings is a significant and typically used activity while coding. Java gives different ways of dividing the String. The most widely recognized way is to use the...

3 minutes read.

Java Boolean equals() method

The equals() method of Java Boolean class returns a Boolean value true if the specified argument is not null and is same as this object, else it returns false. Syntax public boolean...

2 minutes read.

Prime Points in Java

The points that divide an integer into two halves containing a prime number are known as prime points. Printing every prime point of a specific number is the task. Let's...

6 minutes read.