Next Permutation
Time limit1sMemory limit128 MB
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 . Among all integers whose digits are a rearrangement (a permutation) of the digits of , find the smallest one that is strictly greater than — in other words, the next larger permutation of ; call it .
For example, if , the next larger permutation is .
If 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 , the number of test cases. Each of the following lines contains a single integer ().
Output
For each test case, print the next larger permutation of on its own line. If it does not exist, print USELESS.