


The first line of input contains an integer ‘T’, denoting the number of test cases.
The first line of each test case contains an integers ‘N’, denoting Alice’s number.
For each test case, print a single integer denoting the final number after rearranging the digits or -1 when no such number exists.
You are not required to print the expected output. It has already been taken care of. Just implement the function.
1 <= T <= 10
2 <= N <= 2 * (10^9)
Time Limit: 1 sec
Bob needs to find a permutation of the digits of Alice’s number such that it is greater than Alice’s number but is smallest among all the other permutations greater than that of Alice’s number.
So we can convert the number into a string and find all possible permutations of the string. Among all the permutations, we need to find the minimum string greater than that of Alice’s number.
We need to find the next permutation lexicographically of the digits of Alice’s number.
Some key observations are :
So, we can iterate in reverse order storing the maximum digit, and once we find a digit that is smaller than the maximum digit, we need to swap that digit with the smallest digit that is towards the right side and is greater than that digit. In the end, we need to sort the rest of the elements towards the right. For example, 23576, we can swap 5 and 6 to get 23675 and then sort the remaining elements towards the right to get 23657.