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.


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.


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.


1 5 4 8 3
1 4 7 4 5 8 4 1 2 6


hide comments
pyrojathon: 2017-12-29 17:56:52

whats wrong with this code ?

owl_a: 2017-12-23 19:53:00

Same code shows Passed on Geeksforgeeks but wrong answer here. Is there a case I'm missing ?

ritwikshanker: 2017-12-14 16:55:02

Getting TLE in JAVA. SHITTY SPOJ!!! Same soln in c++ submitted. They need to check their time limit for each language.

epsilonalpha: 2017-11-25 02:27:09

AC in 1 go. :)

bhavi736: 2017-11-13 11:18:44

Last edit: 2017-11-13 11:50:03
bir1997: 2017-10-25 16:40:32

no need of any stl or any special fns!!

shauryauppal: 2017-10-05 19:16:58


How next_permutation works one must know? This helped a lot the diagram explanation.

vivaangupta: 2017-10-04 17:43:01


saurav52: 2017-08-26 21:58:49

Did without STL :)

laxman2405: 2017-07-26 14:27:16

Dont forget the case of -1. Costed me 1WA

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