Given a non-negative number N in the form of string. The task is to apply at most one swap operation on the number N so that the resultant is smaller than N and is the largest such number.
Input :str = "12435" Output : 12345 Although the number 12354 will be the largest smaller number from 12435. But it is not possible to make it using only one swap. So swap 4 and 3 and get 12345. Input : 34123567 Output : 33124567 We swap 4 with 3 (on its right side) to get the largest smaller number. Input : str = " 12345" Output : -1 Digits are in increasing order. So it is not possible to make a smaller number from it.
Recommended: Please solve it on “PRACTICE” first, before moving on to the solution.
- Start traversing from right, find a digit is which is greater than one of the digits on its right. Let this index such element be index.
- Then find another index on right of str[index] which holds the greatest value smaller than str[index].
- Swap two values found 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
- Largest even number possible by using one swap operation in given number
- Next higher number using atmost one swap operation
- Form the smallest number using at most one swap operation
- Find the largest number smaller than integer N with maximum number of set bits
- Find largest number smaller than N with same set of digits
- Largest number smaller than or equal to N divisible by K
- Largest number with one swap allowed
- Largest number smaller than or equal to n and digits in non-decreasing order
- Maximize number of groups formed with size not smaller than its largest element
- Previous perfect square and cube number smaller than number N
- Find the closest and smaller tidy number
- Maximize a number considering permutations with values smaller than limit
- Maximum possible number with the given operation
- Minimum possible number with the given operation
- Check if X and Y can be made zero by using given operation any number of times
- Generate number with given operation and check if it is palindrome
- Number of ways to color N-K blocks using given operation
- Count the total number of triangles after Nth operation
- Minimum number of given operation required to convert n to m
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 Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.