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