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

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

hide comments
2020-09-03 15:05:52
@nayan_awati01 Output for your test case must be 768
2020-09-02 18:02:14
i think you must try 687
output must be
786
2020-08-28 17:53:39
run for
1
5
5 7 7 7 7
o/p: 75777
2020-08-17 16:00:03
ck_17 for your TC my ans- 2837799...
2020-08-06 07:24:22
Try to learn how next_permutation works then implement it by your own.
https://www.geeksforgeeks.org/find-the-next-lexicographically-greater-word-than-a-given-word/
2020-07-29 23:16:23
You can try these
2
3
1 0 1
5
1 0 9 8 7
2020-07-24 09:15:31
How can I solve this by using stack?
2020-07-12 15:44:15
Whats the logic to solve it using stack ?
2020-07-10 15:53:35
just use next_permutation. suppose if next permutation returns false just cout -1
2020-07-09 17:27:50
very simple!! well as others have suggested next_permutation to understand what is next_permutation follow this case
7
2 7 9 9 8 7 3

Last edit: 2020-07-11 15:37:22
© Spoj.com. All Rights Reserved. Spoj uses Sphere Engine™ © by Sphere Research Labs.