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 challenged 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
nitin_uniyal21: 2019-07-02 12:45:37

accepted with python 3. Optimize your code

hitesh87: 2019-05-23 18:29:32

Print array!! Don't print number Costed 2 WA

annie181100: 2019-05-07 08:22:56

For an editorial, view this :
https://www.youtube.com/watch?v=t_TMt_BFGiQ

hardik712: 2019-05-02 12:24:19

why its TLE even though if we use next_permutation?

sajanch: 2019-04-26 18:43:26

Why am I getting a TLE in linear time solution in Java? I have used Fast I/O too.

Last edit: 2019-04-26 18:44:11
tensor08: 2019-04-25 15:29:56

Is there any way to do it in linear time or using Stack?

vivek_01: 2019-03-20 19:52:22

Quite easy ,
NlogN in worst case would work fine
used multiset and upper_bounds.....
matter of seconds

aditya_305: 2019-01-30 14:02:19

Done using next_permution function in c++ STL.. LOL

dex_coder007: 2018-12-06 12:44:59

How to do it with stacks?

debsourav33: 2018-10-31 14:09:43

Alright! Done using sorting! Previous O(NlogN) solution using multiset gave TLE but stl sort works! Guess STL sort has slightly better than NlogN runtime..


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