Help on SPOJ JNEXT problem

Hello Chefs, will you please help me finding the NZEC error in the following code for problem - https://www.spoj.com/problems/JNEXT/ :

for _ in range(int(input())):
n = int(input())
l = list(map(int,input().split()))
f = True
for i in range(n-1,1,-1):
    if l[i]>l[i-1]:
        d1 = l[i-1]
        ind = i
        f = False
        break
if f:
    print(-1)
else:
    mi = 9
    d2 = 9
    for i in range(ind,n,1):
        if l[i]>d1 and l[i]<=mi:
            if d2 > l[i]:
                d2 = l[i]
                ind1 = i
            mi = l[i]
    l[ind-1],l[ind1] = l[ind1],l[ind-1]
    l[ind:] = l[n-1:ind-1:-1]
    print(''.join(map(str,l)))

TCs:
4
5
3 2 8 4 1
5
3 2 8 7 6
5
1 5 4 8 3
10
1 4 7 4 5 8 4 1 2 6