Given a non-negative number num. The problem is to find the smallest number greater than num by performing atmost on swap operation between any two digits in num. If no larger number can be formed then print “Not Possible”.
The number could be very large and may not even fit into long long int.
Input : num = "218765" Output : 258761 We swap 5 and 1 to get the smallest number greater than 'num' Input : num = "541322" Output : 542312
Approach: First find the index of the rightmost digit which has a digit larger than it and is on the right side to it. Let its index be ind. Now, find the index of the smallest digit greater than the digit at index ind and is right to it. Let its index be greatSmallDgt. Finally swap the digits at the indexes ind and greatSmallDgt. If the digits of num are in decreasing order then print “Not Possible”.
Original number: 218765 Next higher number: 258761
Time Complexity: O(n), where n is the number of digits in num.
This article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Form the largest number using at most one swap operation
- Form the smallest number using at most one swap operation
- Largest smaller number possible using only one swap operation
- Largest even number possible by using one swap operation in given number
- Next higher palindromic number using the same set of digits
- Sum of all numbers formed having 4 atmost X times, 5 atmost Y times and 6 atmost Z times
- Form the largest palindromic number using atmost two swaps
- Largest number with one swap allowed
- Number of ways to swap two bit of s1 so that bitwise OR of s1 and s2 changes
- Maximum possible number with the given operation
- Minimum possible number with the given operation
- Maximum length prefix such that frequency of each character is atmost number of characters with minimum frequency
- Generate number with given operation and check if it is palindrome
- Number of ways to color N-K blocks using given operation
- Minimum number of given operation required to convert n to m
- Transform One String to Another using Minimum Number of Given Operation
- Check if X and Y can be made zero by using given operation any number of times
- Count the total number of triangles after Nth operation
- Check if the given array can be reduced to zeros with the given operation performed given number of times
- Longest subsequence having difference atmost K
Improved By : Mithun Kumar