while True:
    try:
        T = int(input())
        for _ in range(T):
            n = int(input())
            s = input()
            if len(s) == 2 and s[0] != s[1]:    
                print(-1)
            else:
                s = s + s   # 拼接字符串,方便处理循环字符串的问题
                pos = {}    # 记录每个字符最后一次出现的位置
                ans = n - 1     # 最小距离
                for i, j in enumerate(s):
                    if j in pos:
                        ans = min(ans, i - pos[j] - 1)
                    pos[j] = i
                if ans == n - 1:    # 字符串中每一个字符都不相同
                    print(-1)
                else:
                    print(ans)
    except:
        break