Lexicographically previous permutation
Easy Accuracy: 41.2% Submissions: 652 Points: 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

to report an issue on this page.

Editorial

We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial?

Yes

All Submissions

My Submissions:

Login to access your submissions.