import sys input=lambda: sys.stdin.readline().rstrip() n=int(input()) A=[int(i) for i in input().split()] if n<=2: print(0) elif len(set(A))==1: print(0) else: chk=0 while True: if A[-1]==A[0]: A.pop() chk=1 else: break prev=0 C=set() for i,a in enumerate(A): if a==prev: continue else: if a in C: print(-1) break else: C.add(a) prev=a else: print(chk)