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 email@example.com. 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.
- Largest even number possible by using one swap operation in given number
- Next higher palindromic number using the same set of digits
- 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
- Transform One String to Another using Minimum Number of Given Operation
- Maximise the sum of two Numbers using at most one swap between them
- Form the largest palindromic number using atmost two swaps
- Check if one string can be converted to other using given operation
- Largest number with one swap allowed
- Meta Strings (Check if two strings can become same after a swap in one string)
- Length of longest consecutive ones by at most one swap in a Binary String
- Lexicographically largest string possible in one swap
- Maximum length prefix such that frequency of each character is atmost number of characters with minimum frequency
- Longest subsequence having difference atmost K
- Longest suffix such that occurrence of each character is less than N after deleting atmost K characters
- Longest substring with atmost K characters from the given set of characters
- Binary representation of next greater number with same number of 1's and 0's
- Count changes in Led Lights to display digits one by one
- Sub-strings that start and end with one character and have at least one other
Improved By : Mithun Kumar