import sys

def isDom(xx):
    # print(xx)
    c=0
    mx=max(xx)
    if(mx==1):
        return False
    for i in xx:
        if(i>=mx):
            c+=1
    # print(xx,c)
    if(c==1):
        # print(xx)
        return True
        
    else:
        return False
    
def fun(a,x):
    # if(x==1):
    #     return False
    if(x<=1):
        return False
    xx=[0]*(len(a)+1)
    mx=0
    for i in a[:x]:
        xx[i]+=1
        # mx=max(mx,xx[i])
    # print(xx)
    if(isDom(xx)):
        return True
    else:
        i=x
        # print(xx)
        while(i<len(a)):
            xx[a[i-x]]-=1
            xx[a[i]]+=1
            # mx=max(xx)
            # print(xx,i,a)
            if(isDom(xx)):
                return True
            i+=1
    return False
    
        
t=int(sys.stdin.readline())
for i in range(t):
    n=int(sys.stdin.readline())
    a=list(map(int,sys.stdin.readline().strip().split()))
    if(n==1):
        print(-1)
        continue
    l=1
    r=len(a)
    x=(l+r)//2
    while(r>=l):
        # print(x)
        if(l==r):
            if(fun(a,l) and (not fun(a,l-1))):
                print(l)
            else:
                if(fun(a,l-3)):
                    print(l-3)
                elif(fun(a,l-2)):
                    print(l-2)
                elif(fun(a,l-1)):
                    print(l-1)
                elif(fun(a,min(len(a),l+1))):
                    print(l+1)
                else:
                    print(-1)
            break
        if(fun(a,x)):
            r=x
            x=(l+r)//2
        else:
            l=x+1
            x=(l+r)//2
            # print(l,r,x)
    if(r<l):
        if(fun(a,l) and (not fun(a,l-1))):
            print(l)
        else:
            if(fun(a,l-3)):
                print(l-3)
            elif(fun(a,l-2)):
                print(l-2)
            elif(fun(a,l-1)):
                print(l-1)
            elif(fun(a,min(len(a),l+1))):
                print(l+1)
            else:
                print(-1)