from collections import * N = int(input()) A = list(map(int, input().split())) if N == 2: print(0) exit() ans = 0 c = -1 if A[0] == A[-1]: c = A[0] A = deque(A) while A: if A[0] == c: A.popleft() else: break while A: if A[-1] == c: A.pop() else: break A = list(A) if A == []: print(0) exit() ans = 1 seen = [0] * (N + 1) pre = -1 for a in A: if (a != pre and seen[a]) or a == c: print(-1) exit() pre = a seen[a] = 1 print(ans)