Loading...
Loading...
Neha's hostel locker opens with a code of digits. Every week she changes it to the next larger code that uses exactly the same digits. Codes may start with 0, and all codes have the same length.
Print the next code. If the current code is already the largest arrangement of its digits, start again: print the smallest arrangement (the digits in increasing order).
Example 1
Input
1243
Output
1324
The arrangements just above 1243 start with 13, and the smallest of them is 1324.
Example 2
Input
321
Output
123
321 is the largest arrangement, so the code starts again from 123.
Try the problem first. Open one hint at a time.
To get the next larger code, change as few digits at the end as possible.
Scan from the right and find the first digit that is smaller than the digit after it. Everything to its right is in decreasing order.
Swap that digit with the smallest digit on its right that is still larger than it. Look for it from the right end.
After the swap the tail is still in decreasing order. Reverse the tail to make it as small as possible. If no digit was found in the first scan, reverse the whole code.
Write your Java code, run it on the examples and submit it to hidden tests.
Solve in the editor