import sys def main(): n, *rest = map(int, sys.stdin.read().split()) a = rest[:n] first = {} last = {} for i in range(n): if a[i] not in first: first[a[i]] = i last[a[i]] = i # Check if already valid valid = True for c in first: f = first[c] l = last[c] for i in range(f, l+1): if a[i] != c: valid = False break if not valid: break if valid: print(0) return # Generate candidates for possible rotation candidates = set() for c in first: pos = last[c] + 1 if pos > n: pos = 0 candidates.add(pos % n) candidates.add(0) # Check each candidate for k in sorted(candidates): # Rotate the array: elements from k to end + start to k-1 rotated = a[k:] + a[:k] # Check each color's continuity in the rotated array rot_first = {} rot_last = {} for i in range(len(rotated)): c = rotated[i] if c not in rot_first: rot_first[c] = i rot_last[c] = i is_ok = True for c in rot_first: f = rot_first[c] l = rot_last[c] for i in range(f, l+1): if rotated[i] != c: is_ok = False break if not is_ok: break if is_ok: required_ops = 1 if k != 0 else 0 print(required_ops) return print(-1) if __name__ == '__main__': main()