N=int(input()) if N==1: print(0) exit() A=list(map(int,input().split())) B=[False]*N P=0 if len(set(A))==1: print(0) exit() if A[0]==A[-1]: for i in range(N-1,-1,-1): if A[0]==A[i]: del A[i] P=1 for i in range(len(A)-1): B[A[i]-1]=True if B[A[i+1]-1] and (A[i]!=A[i+1]): print(-1) exit() print(P)