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
karandeep09: 2020-03-03 12:14:30

AC in one go

piyush490: 2020-02-19 18:40:04

Reversing dosen't work
You have to sort the remaining array.

raipavitra: 2020-02-13 10:41:39

just use next_permutation with some pruning.

sayal_hajare: 2020-02-09 17:58:17

My idea: scan from right, and the first time you see the next digit smaller than current, swap them and print; if you don't see any, print -1.

But this is giving WA. Any idea what's wrong?

runmachine__18: 2020-01-20 20:31:48

just solved it in O(n)

bhagyasingh012: 2020-01-20 14:22:42

Finally did it!!

princebaweja1: 2020-01-08 18:19:29

@blank97 no

shreyakjain14: 2020-01-05 04:25:43

why am i getting wrong answer?

blank97: 2019-12-18 18:45:42

does the n digits can contain negative numbers too ?

sd327: 2019-12-02 12:02:41

I am trying to do it in Python3. I am getting runtime error. What to do?


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