JNEXT - Just Next !!!


DevG likes too much fun to do with numbers. Once his friend Arya came and gave him a challenge, he gave DevG an array of digits which is forming a number currently (will be called as given number). DevG was challanged to find the just next greater number which can be formed using digits of given number. Now DevG needs your help to find that just next greater number and win the challenge.

Input

The first line have t number of test cases (1 <= t <= 100). In next 2*t lines for each test case first there is number n (1 <= n <= 1000000) which denotes the number of digits in given number and next line contains n digits of given number separated by space.

Output

Print the just next greater number if possible else print -1 in one line for each test case.

Note : There will be no test case which contains zero in starting digits of any given number.

Example

Input:
2
5
1 5 4 8 3
10
1 4 7 4 5 8 4 1 2 6

Output:
15834
1474584162

hide comments
cuunon311: 2024-04-04 18:38:56

EZ :3

pb2008: 2024-03-07 06:09:21

ez. ac in 23 second (if you get WA use multi_set)

king_87arshia: 2024-03-07 06:07:29

AC in zero GO! bigbigy

amirmbz_86: 2024-03-07 06:07:08

AC in zero GO!
too EZ segment tree!

bigbardia: 2024-03-06 17:09:55

AC in one GO!

vantien1526: 2023-08-18 15:02:33

use stack

kavascgjmd: 2023-01-29 06:26:46

30780649 30780647 what's wrong in the above

nowshadsub15: 2022-04-12 10:00:30

Solved without stack, used sorting and frequency table of 1 to 9

manurag_20: 2022-02-22 11:11:46

try greedy : )

hellooo: 2022-01-10 10:11:55

I wonder how multiset still passes, although it is O(n log n)


Added by:! include(L.ppt)
Date:2012-08-31
Time limit:1.297s
Source limit:50000B
Memory limit:1536MB
Cluster: Cube (Intel G860)
Languages:All except: ASM64
Resource:MNNIT OPC 31-08-2012