Next Permutation

Time limit1sMemory limit128 MB

Summary
Given an integer A, find the smallest permutation of its digits that is strictly greater than A, or print USELESS if none exists.
Level

Medium4 of 10

Topics
Array, String, Greedy, Two pointers
Solved
No attempts yet

Problem

You are given a positive integer AA. Among all integers whose digits are a rearrangement (a permutation) of the digits of AA, find the smallest one that is strictly greater than AA — in other words, the next larger permutation of AA; call it BB.

For example, if A=2413A = 2413, the next larger permutation is 24312431.

If AA is already the largest number that can be formed from its digits (no larger permutation exists), print USELESS instead.

Input

The first line contains an integer TT, the number of test cases. Each of the following TT lines contains a single integer AA (A≤2,000,000A \le 2{,}000{,}000).

Output

For each test case, print the next larger permutation BB of AA on its own line. If it does not exist, print USELESS.

Examples5

  1. Example 1

    Input
    4
    237531
    1234
    4321
    3444
    
    Expected output
    251337
    1243
    USELESS
    4344
    
  2. Example 2

    Input
    3
    5
    21
    111
    
    Expected output
    USELESS
    USELESS
    USELESS
    
  3. Example 3

    Input
    2
    12
    1234
    
    Expected output
    21
    1243
    
  4. Example 4

    Input
    3
    115
    151
    511
    
    Expected output
    151
    511
    USELESS
    
  5. Example 5

    Input
    2
    2413
    2431
    
    Expected output
    2431
    3124