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
raghav2130: 2022-01-05 11:26:01

next_permutation has a TC of N*N!
(printing all permutation)
thus you will most probably get a TLE.
it is stack and queue based question.

vinoth0708: 2021-11-10 09:40:51

why we use next_permutation just simple approach

mnnit_1: 2021-10-30 10:48:36

nayan_awati01 for 687 o/p will be 768 not 786

aniket_7781: 2021-06-27 18:29:24

dont miss (-1) condition ;(

Last edit: 2021-06-27 18:30:33
utkarsh0124: 2021-03-04 05:42:36

@gnomegeek no need for sorting, it will be an overhead. Can be done in linear time O(n). Stacks will do just fine.
code:- <snip>

[NG]: Stop posting code or you'll find yourself banned from comenting.

Last edit: 2021-03-04 11:52:40
gnomegeek: 2021-01-26 19:50:23

medium difficulty. Need to use sort, stack and logic <3. lovely question.

satyamkr118: 2020-12-04 06:50:17

My soln is not getting accepted even if i am doing after watching tutorial.

varun1997: 2020-10-06 12:06:46

Stack is helpful in finding just next smaller element then what is already in tos! May this hint helps!

gauris_17: 2020-09-21 10:53:33

How to solve it using stack?

scrapperdb: 2020-09-03 15:19:49

@zerothking @mr_code_art this can be solved using queue.


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