![]() |
VOOZH | about |
Given a number N as string, find the smallest number that has same set of digits as N and is greater than N. If N is the greatest possible number with its set of digits, then print "Not Possible".
Examples:
Input: N = "218765"
Output: "251678"
Explanation: The next number greater than 218765 with same set of digits is 251678.Input: n = "1234"
Output: "1243"
Explanation: The next number greater than 1234 with same set of digits is 1243.Input: n = "4321"
Output: "Not Possible"
Explanation: 4321 is the greatest number possible with same set of digits.\
Table of Content
Find all the possible permutations of the given string and then for each permutation, check if it greater than N or not. Among all the strings which are greater than N, the smallest one is the answer.
On observing carefully, we can say that the next number which is greater than N and has the same digits as N is the next permutation of string N. We can simply find the next permutation by following the below steps:
- Traverse the given number from rightmost digit, keep traversing till you find a digit which is smaller than the previously traversed digit. For example, if the input number is "534976", we stop at 4 because 4 is smaller than next digit 9. If we do not find such a digit, then output is "Not Possible".
- Now search the right side of above found digit 'd' for the smallest digit greater than 'd'. For "534976", the right side of 4 contains "976". The smallest digit greater than 4 is 6.
- Swap the above found two digits, we get 536974 in above example.
- Now reverse all digits from position next to 'd' to the end of number to get the result. For above example, we reverse the digits in bold 536974. We get "536479" which is the next greater number for input 534976..
Below is the implementation of the above approach:
251678
Time Complexity: O(N), where N is the number of digits in input, that is the length of string.
Auxiliary Space: O(1)