mod = 1000000007 eps = 10**-9 def main(): import sys input = sys.stdin.readline N = int(input()) A = list(map(int, input().split())) pos = [[] for _ in range(N+1)] for i, a in enumerate(A): pos[a].append(i) flg = 0 for a in range(N): if pos[a]: L = len(pos[a]) prev = pos[a][0] if prev != 0: for i in pos[a][1:]: if i != prev + 1: print(-1) exit() else: prev = i else: for i in range(1, L): ii = pos[a][i] if ii != prev + 1: flg = 1 j = i-1 break else: prev = ii if flg: prev = N for i in range(L-1, j, -1): ii = pos[a][i] if ii != prev - 1: print(-1) exit() else: prev = ii print(flg) if __name__ == '__main__': main()