## Next Greater Number with Same Set of Digits in JavaA number (num) is given. The task is to find a number that is the smallest that comprises the same set of digits as num and must be larger than the number num. If the number num is the largest number possible with its digits set, then it is not possible to find the next greater number, and hence, a message should be displayed accordingly.
98123, 98132, 98213, 98231, 98312, 98321, 93128, 93182, 93218, 93281, 93812, 93821, 92138, 92183, 92318, 92381, 92813, 92831, 91238, 91283, 91328, 91382, 91823, 91832 In all these number the smallest number is 91238.
3684, 4368, 4386, 4638, 4683, 4836, 4863, 6348, 6384, 6438, 6483, 6834, 6843, 8346, 8364, 8436, 8463, 8634, 8643 In all these number the smallest number is 3684.
## ObservationThe following are some of the important points of observation. - If the digits of a number are being arranged in the descending order, then the result is "It is not possible to find the next greater number". For example, 98675.
- If the digits of a number are being arranged in the ascending order, then one needs to interchange the last two digits of the number. For example, for the number 4567, the next greater number is 4576.
- For the rest of the other cases, one needs to begin the processing of the number from the rightmost side as one has to find the smallest among the numbers that are larger than the given number.
## AlgorithmThe following is the algorithm for computing the next greater number on the basis of the observation described above.
## Using PermutationIt is a brute force approach. In this approach, we will be computing each number that can be formed using the digits present in the given number num. We will be storing those computed numbers in a hash set
For the number: 536479 The next greater number is: 536497 For the number: 654321 The next greater number is not possible. For the number: 4876 The next greater number is: 6478
## Using Sorting
For the number: 536479 The next greater number is: 536497 For the number: 654321 The next greater number is not possible. For the number: 4876 The next greater number is: 6478
## Note: We can even reduce the time complexity further. Note that instead of sorting, we can also use the inbuild reverse method to do the sorting. It is because the digits that we are sorting are arranged in descending order. For example, sorting 6, 5, 4, 3, 2, 1 should not take O(n x log(n)) time. Only reversing the order will do the job. So, instead of sorting, use the reverse() method to reduce the time complexity to O(n).In the method isSwapPossible(), make the following changes to get the same result. |

For Videos Join Our Youtube Channel: Join Now

- Send your Feedback to [email protected]