Lexicographically previous permutation
Submissions: 544   Accuracy:

40.38%

  Difficulty: Easy   Marks: 2

Given a word, find lexicographically smaller permutation of it.
For example lexicographically smaller permutation of “4321” is “4312” and next smaller permutation of “4312” is “4231”. If the string is sorted in ascending order, the next lexicographically smaller permutation doesn’t exist.
 

Input:

The first line of input contains a single integer T denoting the number of test cases. Then T test cases follow. Each test case consist of one line. The first line of each test case consists of a string S.
 

Output:

Corresponding to each test case, in a new line, print the lexicographically smaller permutation of it. If the string is sorted in ascending order then print -1.
 

Constraints:

1 ≤ T ≤ 100
1 ≤ string length (S) ≤ 7

Example:

Input
2
4321
1234

Output
4312

-1

** For More Input/Output Examples Use 'Expected Output' option **

Author: rajatjha


If you have purchased any course from GeeksforGeeks then please ask your doubt on course discussion forum. You will get quick replies from GFG Moderators there.



Need help with your code? Please use ide.geeksforgeeks.org, generate link and share the link here.


to report an issue on this page.