import sys from collections import defaultdict def main(): N = int(sys.stdin.readline()) A = list(map(int, sys.stdin.readline().split())) count = defaultdict(int) last = {} for i in range(N): c = A[i] count[c] += 1 last[c] = i # 0-based # Sort colors based on their last occurrence sorted_colors = sorted(last.keys(), key=lambda x: last[x]) # Construct the target array T T = [] for c in sorted_colors: T.extend([c] * count[c]) if T == A: print(0) return # Check if T is a cyclic shift of A (i.e., exists in A + A) s = A + A pattern = T len_pat = len(pattern) len_text = len(s) # KMP algorithm to check if pattern is a substring of s # Build prefix array (LPS) lps = [0] * len_pat length = 0 # length of the previous longest prefix suffix i = 1 while i < len_pat: if pattern[i] == pattern[length]: length += 1 lps[i] = length i += 1 else: if length != 0: length = lps[length - 1] else: lps[i] = 0 i += 1 # Search using KMP i = j = 0 found = False while i < len_text: if s[i] == pattern[j]: i += 1 j += 1 if j == len_pat: found = True break else: if j != 0: j = lps[j - 1] else: i += 1 if found: print(1) else: print(-1) if __name__ == "__main__": main()