One day, Twilight Sparkle is interested in how to sort a sequence of integers a_1, a_2, ..., a_{n} in non-decreasing order. Being a young unicorn, the only operation she can perform is a unit shift. That is, she can move the last element of the sequence to its beginning:a_1, a_2, ..., a_{n} → a_{n}, a_1, a_2, ..., a_{n} - 1. 

Help Twilight Sparkle to calculate: what is the minimum number of operations that she needs to sort the sequence?


-----Input-----

The first line contains an integer n (2 ≤ n ≤ 10^5). The second line contains n integer numbers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^5).


-----Output-----

If it's impossible to sort the sequence output -1. Otherwise output the minimum number of operations Twilight Sparkle needs to sort it.


-----Examples-----
Input
2
2 1

Output
1

Input
3
1 3 2

Output
-1

Input
2
1 2

Output
0

Difficulty: EASY
Tags: Implementation

Starter code:

Solutions:
def main():
	from sys import stdin, stdout
	n = int(stdin.readline())
	tup = tuple(map(int, stdin.readline().split()))
	minim = min(tup)
	maxim = max(tup)
	maximindex = tup.index(maxim)
	flag = 1
	i = 0
	pv = tup[-1]
	while i < n:
		if tup[i] < pv:
			if tup[i] == minim and pv == maxim:
				l = i + 1
				while l < max(maximindex, n):
					if tup[l] < tup[l - 1]:
						flag = 0
						break
					l += 1
				break
			else:
				flag = 0
				break
		pv = tup[i]
		i += 1
	if flag:
		if i:
			stdout.write(str(n - i))
		else:
			stdout.write('0')
	else:
		stdout.write('-1')
main()


from sys import stdin, stdout

def shift(alist):
	return [alist[len(alist) - 1]] + alist[:len(alist) - 1]

def solve(ints, n):
	i = 0
	while i < n - 1:
		if ints[i] > ints[i + 1]:
			sliced = ints[i + 1:]
			if sliced == sorted(sliced) and sliced[len(sliced) - 1] <= ints[0]:
				return len(sliced)
			return -1
		i += 1
	return 0
n = int(stdin.readline().rstrip())
integers = list(map(int, stdin.readline().rstrip().split()))
stdout.write(str(solve(integers, n)))


import sys
input = sys.stdin.readline
n = int(input())
a = list(map(int, input().split()))
qw = []
for i in range(len(a) - 1):
	if a[i] > a[i + 1]:
		qw = a[i + 1:] + a[:i + 1]
		break
if a == sorted(a):
	print(0)
elif qw == sorted(qw):
	print(len(a) - i - 1)
else:
	print(-1)


def f(a, n):
	i = 1
	while i < n and a[i] >= a[i - 1]:
		i += 1
	if i == n:
		return 0
	else:
		(st1, en1) = (i, n - 1)
		(st2, en2) = (0, i - 1)
		for j in range(st1, en1):
			if a[j] <= a[j + 1]:
				continue
			else:
				return -1
		for j in range(st2, en2):
			if a[j] <= a[j + 1]:
				continue
			else:
				return -1
		if a[0] >= a[-1]:
			return n - i
		else:
			return -1
n = int(input())
a = list(map(int, input().split()))
print(f(a, n))


def cs(a):
	for i in range(len(a) - 1):
		if a[i] > a[i + 1]:
			return False
	return True
n = int(input())
l = list(map(int, input().split()))
if cs(l) == False:
	for i in range(len(l) - 1):
		if l[i] > l[i + 1]:
			if cs(l[i + 1:]) and l[-1] <= l[0]:
				print(len(l) - i - 1)
			else:
				print(-1)
			break
else:
	print(0)


from sys import stdin, stdout
ii1 = lambda : int(stdin.readline().strip())
is1 = lambda : stdin.readline().strip()
iia = lambda : list(map(int, stdin.readline().strip().split()))
isa = lambda : stdin.readline().strip().split()
mod = 1000000007
n = ii1()
arr = iia()
op = False
for i in range(1, n):
	if arr[i] < arr[i - 1]:
		arr = arr[i:] + arr[:i]
		op = True
		break
if arr == sorted(arr):
	if not op:
		print(0)
	else:
		print(n - i)
else:
	print(-1)


size = int(input())
inarr = list(map(int, input().split()))
sortarr = sorted(inarr)
n = 0
if inarr == sortarr:
	print(0)
	exit()
for i in range(len(inarr)):
	if inarr[i] > inarr[i + 1]:
		n = i + 1
		break
if n == 0:
	print(-1)
elif inarr[n:] == sortarr[:-n]:
	print(len(inarr) - n)
else:
	print(-1)


n = int(input())
a = input().split(' ')
pos = -1
valid = True
for i in range(len(a)):
	if i + 1 < len(a):
		if int(a[i]) > int(a[i + 1]):
			if pos == -1:
				pos = i + 1
			else:
				valid = False
if valid and pos == -1:
	pos = 0
ans = pos
if valid:
	for i in range(len(a) - 1):
		n_pos = (int(pos) + 1) % n
		if int(a[pos]) > int(a[n_pos]):
			valid = False
		pos = n_pos
if valid:
	print((n - ans) % n)
else:
	print(-1)


n = int(input())
a = list(map(int, input().split()))
prev = 0
j = 0
for i in range(n):
	if prev > a[i]:
		j = i
		break
	prev = a[i]
na = a[j:] + a[:j]
if na == sorted(a):
	print((n - j) % n)
else:
	print(-1)


n = int(input())
a = [int(i) for i in input().split()]
c = 0
ind = -1
for i in range(1, n):
	if a[i] < a[i - 1]:
		c += 1
		s = i
if c == 0:
	print(0)
elif a[0] >= a[n - 1] and c == 1:
	print(n - s)
else:
	print(-1)


n = int(input())
st = [int(i) for i in input().split()]
for i in range(1, n):
	if st[i - 1] > st[i]:
		print((-1, n - i)[sorted(st) == st[i:] + st[:i]])
		break
else:
	print(0)


n = int(input())
l = [int(x) for x in input().split()]
for i in range(len(l) - 1):
	if l[i] > l[i + 1]:
		if sorted(l) == l[i + 1:] + l[:i + 1]:
			print(n - i - 1)
			exit()
		else:
			print(-1)
			exit()
print(0)


n = list(map(int, input().split()))[0]
a = list(map(int, input().split()))
flag = 0
for i in range(1, n):
	if a[i] < a[i - 1]:
		flag = i
ans = True
for i in range(flag + 1, n - 1):
	if a[i + 1] < a[i]:
		ans = False
for i in range(flag - 1):
	if a[i + 1] < a[i]:
		ans = False
if flag != 0 and a[n - 1] > a[0]:
	ans = False
if not ans:
	print('-1')
else:
	print((n - flag) % n)


import sys
inf = float('inf')
(mod, MOD) = (1000000007, 998244353)
from math import ceil, floor, log, sqrt, factorial, pow, pi, gcd, log10, atan, tan

def get_array():
	return list(map(int, sys.stdin.readline().strip().split()))

def get_ints():
	return map(int, sys.stdin.readline().strip().split())

def get_strs():
	return map(str, sys.stdin.readline().strip().split())

def input():
	return sys.stdin.readline().strip()
n = int(input())
Arr = get_array()
count = 0
for i in range(1, n):
	if Arr[i] < Arr[i - 1]:
		count += 1
		index = n - i
if count == 0:
	print(0)
elif count == 1:
	if Arr[-1] <= Arr[0]:
		print(index)
	else:
		print(-1)
else:
	print(-1)


n = int(input())
l = list(map(int, input().split()))
c = 0
ans = 0
for i in range(1, n):
	if l[i] < l[i - 1]:
		c += 1
		ans = n - i
if c == 1 and l[0] >= l[-1] or c == 0:
	print(ans)
else:
	print(-1)


import sys
n = int(input())
l = [int(i) for i in input().split()]
l += [l[0]]
jump = False
j = -1
m = l[0]
for i in range(n):
	if l[i] > l[i + 1]:
		if jump:
			print(-1)
			sys.exit(0)
		jump = True
		j = i
	elif jump:
		if l[i] > m:
			print(-1)
			sys.exit(0)
if j == -1:
	print(0)
else:
	print(n - j - 1)


import sys
input = sys.stdin.readline
from math import log2, log, ceil

def swaparr(arr, a, b):
	temp = arr[a]
	arr[a] = arr[b]
	arr[b] = temp

def gcd(a, b):
	if a == 0:
		return b
	return gcd(b % a, a)

def nCr(n, k):
	if k > n - k:
		k = n - k
	res = 1
	for i in range(k):
		res = res * (n - i)
		res = res / (i + 1)
	return res

def upper_bound(a, x, lo=0):
	hi = len(a)
	while lo < hi:
		mid = (lo + hi) // 2
		if a[mid] < x:
			lo = mid + 1
		else:
			hi = mid
	return lo

def primefs(n):
	primes = {}
	while n % 2 == 0:
		primes[2] = primes.get(2, 0) + 1
		n = n // 2
	for i in range(3, int(n ** 0.5) + 2, 2):
		while n % i == 0:
			primes[i] = primes.get(i, 0) + 1
			n = n // i
	if n > 2:
		primes[n] = primes.get(n, 0) + 1
	return primes

def power(x, y, p):
	res = 1
	x = x % p
	if x == 0:
		return 0
	while y > 0:
		if y & 1 == 1:
			res = res * x % p
		y = y >> 1
		x = x * x % p
	return res

def swap(a, b):
	temp = a
	a = b
	b = temp
	return (a, b)

def find(x, link):
	while x != link[x]:
		x = link[x]
	return x

def union(x, y, size, link):
	x = find(x, link)
	y = find(y, link)
	if size[x] < size[y]:
		(x, y) = swap(x, y)
	if x != y:
		size[x] += size[y]
		link[y] = x

def sieve(n):
	prime = [True for i in range(n + 1)]
	p = 2
	while p * p <= n:
		if prime[p] == True:
			for i in range(p * p, n + 1, p):
				prime[i] = False
		p += 1
	return prime
MAXN = int(1000000.0 + 5)

def spf_sieve():
	spf[1] = 1
	for i in range(2, MAXN):
		spf[i] = i
	for i in range(4, MAXN, 2):
		spf[i] = 2
	for i in range(3, ceil(MAXN ** 0.5), 2):
		if spf[i] == i:
			for j in range(i * i, MAXN, i):
				if spf[j] == j:
					spf[j] = i

def factoriazation(x):
	ret = {}
	while x != 1:
		ret[spf[x]] = ret.get(spf[x], 0) + 1
		x = x // spf[x]
	return ret

def int_array():
	return list(map(int, input().strip().split()))

def str_array():
	return input().strip().split()
MOD = int(1000000000.0) + 7
CMOD = 998244353
INF = float('inf')
NINF = -float('inf')
n = int(input())
a = int_array()
ind = None
for i in range(len(a) - 1):
	if a[i] > a[i + 1]:
		ind = i + 1
		break
if ind == None:
	print(0)
else:
	a = a[ind:] + a[:ind]
	if a == sorted(a):
		print(len(a[ind:]))
	else:
		print(-1)


n = int(input())
a = list(map(int, input().split()))
b = sorted(a)
if a == b:
	print(0)
else:
	for i in range(1, len(a)):
		if a[i - 1] > a[i]:
			if a[i:] + a[:i] == b:
				print(n - i)
				break
			else:
				print(-1)
				break


n = int(input())
A = list(map(int, input().split()))
maxu = max(A)
ind = A.index(maxu)
while ind < n - 1 and A[ind + 1] == A[ind]:
	ind += 1
flag = 1
for i in range(n - 1):
	if A[(i + ind + 2) % n] >= A[(i + ind + 1) % n]:
		continue
	else:
		print(-1)
		flag = 0
		break
if flag:
	print(n - ind - 1)


n = int(input())
a = list(map(int, input().split()))
(m1, m2) = (a.index(min(a)), a.index(max(a)))
if a == sorted(a):
	print(0)
elif m1 < m2:
	if a == sorted(a):
		print(0)
	elif n - 1 - a[::-1].index(min(a)) <= m2:
		print(-1)
		quit()
	else:
		while a[m2 + 1] == a[m2]:
			m2 += 1
		m1 = m2 + 1
		if m1 == m2 + 1:
			if a[m1 + 1:] == sorted(a[m1 + 1:]):
				if a[:m2] == sorted(a[:m2]):
					if a[-1] <= a[0]:
						print(n - m2 - 1)
						quit()
	print(-1)
else:
	while a[m2 + 1] == a[m2]:
		m2 += 1
		m1 = m2 + 1
	if m1 == m2 + 1:
		if a[m1 + 1:] == sorted(a[m1 + 1:]):
			if a[:m2] == sorted(a[:m2]):
				if a[-1] <= a[0]:
					print(n - m2 - 1)
					quit()
	print(-1)


n = int(input())
L = list(map(int, input().split()))
for i in range(n - 1):
	if L[i] > L[i + 1]:
		print(*[n - i - 1 if sorted(L) == L[i + 1:] + L[:i + 1] else -1])
		quit()
print(0)


import sys
INT_MAX = sys.maxsize
INT_MIN = -sys.maxsize - 1
sys.setrecursionlimit(10 ** 5)
mod = 1000000007

def IOE():
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')

def main():
	n = int(sys.stdin.readline())
	a = list(map(int, sys.stdin.readline().split()))
	inc = [a[0]]
	dec = []
	flag = False
	for i in range(n - 1):
		if a[i + 1] >= a[i] and (not flag):
			inc.append(a[i + 1])
		else:
			flag = True
		if flag:
			dec.append(a[i + 1])
	if dec + inc == sorted(a):
		print(len(dec))
	else:
		print(-1)
try:
	IOE()
except:
	pass
main()


n = int(input())
a = list(map(int, input().split()))
flag = False
for i in range(1, n):
	if a[i] < a[i - 1] and (not flag):
		flag = i
	elif a[i] < a[i - 1] and flag:
		print(-1)
		break
else:
	if n - flag == n:
		print(0)
	elif a[n - 1] <= a[0] and a[flag] <= a[0]:
		print(n - flag)
	else:
		print(-1)


n = int(input().strip())
arr = list(map(int, input().strip().split()))
s = sorted(arr)
if arr == s:
	print(0)
else:
	for i in range(n - 1):
		if arr[i] > arr[i + 1]:
			ind = i
			break
	if arr[ind + 1:] + arr[:ind + 1] == s:
		print(n - ind - 1)
	else:
		print(-1)


import os.path
from math import gcd, floor, ceil
from collections import *
import sys
mod = 1000000007
INF = float('inf')

def st():
	return list(sys.stdin.readline().strip())

def li():
	return list(map(int, sys.stdin.readline().split()))

def mp():
	return map(int, sys.stdin.readline().split())

def inp():
	return int(sys.stdin.readline())

def pr(n):
	return sys.stdout.write(str(n) + '\n')

def prl(n):
	return sys.stdout.write(str(n) + ' ')
if os.path.exists('input.txt'):
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
n = inp()
f = 0
ans = 0
l = li()
ind = -1
for i in range(n - 2, -1, -1):
	if l[i] > l[i + 1]:
		ind = i + 1
		break
if ind == -1:
	pr(0)
else:
	prev = l[-1]
	for i in range(ind):
		if l[i] < prev:
			f = 1
			break
		prev = l[i]
	if f:
		ans = -1
	else:
		ans = n - ind
	pr(ans)


n = int(input())
a = [int(i) for i in input().split()]
d = 0
r = 0
for i in range(1, n):
	if a[i] < a[i - 1]:
		if d:
			d = -1
			break
		elif a[n - 1] <= a[0]:
			d = 1
			r = i
		else:
			d = -1
			break
if d == 1:
	print(n - r)
else:
	print(d)


n = int(input())
a = list(map(int, input().split()))
c = 0
for i in range(1, n):
	if a[i - 1] > a[i]:
		c = i
		break
if c == 0:
	print(0)
	exit()
if a[c] > a[0] or a[-1] > a[0]:
	print(-1)
	exit()
x = 0
y = 0
for i in a[c:]:
	y += 1
	if i < x:
		print(-1)
		exit()
	x = i
print(y)


n = int(input())
a = list(map(int, input().split()))
(f, c) = (1, 1)
for i in range(1, n):
	if f:
		if a[i] < a[i - 1]:
			f = 0
	elif a[i] < a[i - 1]:
		print(-1)
		f = -1
		break
	else:
		c += 1
else:
	if f != -1:
		if f == 1:
			print(0)
		elif a[-1] > a[0]:
			print(-1)
		else:
			print(c)


n = int(input())
a = list(map(int, input().split()))
if a == sorted(a):
	print(0)
else:
	m = a.index(max(a))
	while m < n - 1:
		if a[m] == a[m + 1]:
			m += 1
		else:
			break
	a1 = a[:m + 1]
	a2 = a[m + 1:]
	if a1 == sorted(a1) and a2 == sorted(a2) and (max(a2) <= a1[0]):
		print(n - (m + 1))
	else:
		print(-1)


n = int(input())
a = list(map(int, input().split()))
inv = [False] * n
cnt = 0
for i in range(n):
	if a[i % n] > a[(i + 1) % n]:
		cnt += 1
		inv[i] = True
if cnt == 0:
	print(0)
elif cnt > 1:
	print(-1)
else:
	for i in range(n):
		if inv[i]:
			print(n - i - 1)
			break


n = int(input())
a = list(map(int, input().split()))
if a == sorted(a):
	print(0)
else:
	ind = a.index(max(a))
	while ind < n - 1 and a[ind] == a[ind + 1]:
		ind += 1
	if a[:ind] == sorted(a[:ind]) and a[ind + 1:] == sorted(a[ind + 1:]) and (a[0] >= a[-1]):
		print(n - ind - 1)
	else:
		print(-1)


n = int(input())
A = list(map(int, input().split()))
B = sorted(A)
if B[n - 1] == B[0]:
	print(0)
	exit()
o = 0
for i in range(n):
	if A[i] == B[n - 1] and A[(i + 1) % n] == B[0]:
		o = i + 1
		break
for i in range(n):
	if A[(i + o) % n] != B[i]:
		print(-1)
		exit()
print((n - o) % n)


n = int(input())
a = list(map(int, input().split()))
v = 0
br = 0
for i in range(n - 1):
	if a[i] > a[i + 1]:
		br = i
		v += 1
if a[n - 1] > a[0]:
	br = n - 1
	v += 1
if v == 0:
	print(0)
elif v > 1:
	print(-1)
else:
	print(n - br - 1)


a = int(input())
arr = list(map(int, input().split()))
minn = min(arr)
maxx = max(arr)
k = -1
for i in range(0, len(arr) - 1):
	if arr[i] == maxx and arr[i + 1] == minn:
		k = i
		break
if arr[len(arr) - 1] == maxx and arr[0] == minn:
	k = 0
if k == -1:
	print(-1)
else:
	bef = arr[:k + 1]
	af = arr[k + 1:]
	if sorted(arr) == arr:
		print(0)
	elif sorted(bef) == bef and sorted(af) == af and (arr[0] >= arr[len(arr) - 1]):
		print(len(arr) - k - 1)
	else:
		print(-1)


n = int(input())
sl = list(map(int, input().split()))
p = max(sl)
q = min(sl)
a = -1
k = 0
pp = 10000000000
for i in range(1, n):
	if sl[i] >= sl[i - 1]:
		if a < 0:
			pp = min(pp, sl[i - 1])
		if a >= 0:
			k = max(k, sl[i])
		continue
	elif p == sl[i - 1] and q == sl[i]:
		a += 1
		ans = n - i
	else:
		a = -2
		break
if k > pp:
	a = -2
if a == -1:
	print('0')
elif a == -2 or a > 0:
	print('-1')
elif a == 0:
	print(ans)


N = int(input())
place = N
word = True
numbers = list(map(int, input().split()))
for i in range(1, N):
	if numbers[i] < numbers[i - 1]:
		place = i
		for i in range(place + 1, place + N):
			if numbers[i % N] < numbers[i % N - 1]:
				word = False
				break
		break
if word == False:
	print(-1)
else:
	print(N - place)


def min_moves(n, l):
	(m, k) = (0, 0)
	for i in range(n - 1):
		if l[i + 1] < l[i]:
			return (-1, n - i - 1)[sorted(l) == l[i + 1:] + l[:i + 1]]
			break
	else:
		return 0
n = int(input())
l = list(map(int, input().split()))
print(min_moves(n, l))


def main():
	n = int(input())
	li_str = input().split(' ')
	minval = int(li_str[0])
	min_idx = -1
	for i in range(n):
		if int(li_str[i]) >= minval:
			minval = int(li_str[i])
		elif min_idx == -1:
			min_idx = i
			minval = int(li_str[i])
		else:
			print('-1')
			return 0
	if min_idx == -1:
		print('0')
	else:
		if n == 2:
			if int(li_str[0]) > int(li_str[1]):
				print('1')
			else:
				print('0')
			return 0
		if int(li_str[0]) < int(li_str[n - 1]):
			print('-1')
		else:
			print(str(n - min_idx))
main()


def canBeOrdered(n, arr):
	s = 0
	v = 0
	for i in range(len(arr) - 1):
		if arr[i] > arr[i + 1]:
			s = i
			v += 1
	if arr[n - 1] > arr[0]:
		s = n - 1
		v += 1
	if v == 0:
		return 0
	elif v > 1:
		return -1
	else:
		return n - 1 - s
n = int(input())
arr = [int(i) for i in input().split()]
print(canBeOrdered(n, arr))


N = int(input())
A = list(map(int, input().split()))
sp = 1
while sp < N:
	if A[sp - 1] <= A[sp]:
		sp += 1
	else:
		break
new_l = A[sp:] + A[:sp]
sorted_new_l = sorted(new_l)
for i in range(N):
	if new_l[i] != sorted_new_l[i]:
		print(-1)
		exit()
ans = N - sp
print(ans)


n = int(input())
a = list(map(int, input().split()))
if n == 2:
	if a[0] <= a[1]:
		print(0)
	else:
		print(1)
else:
	pos = 1
	flag = 0
	for i in range(n - 1):
		if a[i] <= a[i + 1]:
			pos += 1
			flag = 1
		else:
			if i == 0 or flag == 1:
				if a[n - 1] <= a[0]:
					for j in range(pos, n - 1):
						if a[j] <= a[j + 1]:
							flag = 1
						else:
							flag = 0
							pos = -1
							break
				else:
					flag = 0
					pos = -1
					break
			else:
				flag = 0
				pos = -1
				break
			break
	if flag == 0:
		print(pos)
	else:
		print(n - pos)


n = int(input())
ar = list(map(int, input().split()))
count = 0
flag = False

def test():
	global count
	global flag
	min = 999999999999
	for i in range(n - 1):
		if not flag:
			if ar[i] < min:
				min = ar[i]
		if ar[i] > ar[i + 1] and flag:
			return False
		elif ar[i] > ar[i + 1] and (not flag):
			if ar[i + 1] > min:
				return False
			flag = True
			count += 1
		elif ar[i] <= ar[i + 1] and flag:
			if ar[i + 1] > min:
				return False
			count += 1
		elif ar[i] <= ar[i + 1] and (not flag):
			continue
	return True
if test():
	print(count)
else:
	print('-1')


n = int(input())
li = list(map(int, input().split()))
c = n
for i in range(1, n):
	if li[i] < li[i - 1]:
		c = i
		break
li2 = li[c:n] + li[0:c]
if li2 == sorted(li):
	print(n - c)
else:
	print(-1)


n = int(input())
a = list(map(int, input().strip().split(' ')))
idx = 0
while idx < len(a) - 1 and a[idx] <= a[idx + 1]:
	idx += 1
idx += 1
step = 0
while idx < len(a) and a[idx] <= a[(idx + 1) % len(a)] and (a[idx] <= a[0]):
	idx += 1
	step += 1
if idx == len(a):
	print(step)
else:
	print('-1')


n = int(input())
s = list(map(int, input().split()))
for x in range(1, n):
	if s[x - 1] > s[x]:
		print((-1, n - x)[sorted(s) == s[x:] + s[:x]])
		break
else:
	print(0)


def solve(arr):
	t = arr + arr
	count = 0
	offset = 0
	for i in range(len(arr)):
		if t[i] > t[i + 1]:
			count += 1
			offset = i + 1
	if count > 1:
		return -1
	return 0 if offset == 0 else len(arr) - offset
input()
res = solve(list(map(int, input().split())))
print(res)


n = int(input())
l = list(map(int, input().split()))
if n == 2 and l[0] <= l[1]:
	print(0)
	exit(0)
mini = l[0]
inc = 0
dec = 0
ans = 0
sax = 0
for i in range(n - 1):
	if l[i] <= l[i + 1]:
		if dec == 0:
			mini = min(l[i], l[i - 1])
		inc = 1
		if dec == 1:
			ans += 1
	else:
		ans += 1
		dec += 1
	if inc and dec > 1:
		print(-1)
		exit(0)
	if inc and dec == 1 and (l[i + 1] > mini):
		print(-1)
		exit(0)
	if dec > 1:
		print(-1)
		exit(0)
print(ans)


n = int(input())
a = list(map(int, input().split()))
k = 0
c = min(a)
ind = a.index(c)
p = len(set(a))
while ind == 0 and a[-1] == c and (p != 1):
	a.insert(0, a.pop())
	k += 1
if ind != 0:
	a = a[ind:] + a[:ind]
	k += n - ind
if a == sorted(a):
	print(k)
else:
	print('-1')


n = int(input())
a = list(map(int, input().split()))
k = 0
for i in range(n - 1):
	if a[i] > a[i + 1]:
		k += 1
if k == 0:
	print(0)
elif k > 1 or a[n - 1] > a[0]:
	print(-1)
else:
	for i in range(n):
		if a[i] > a[i + 1]:
			print(n - i - 1)
			break


n = int(input())
l = [int(i) for i in input().split()]
k = 0
for i in range(n - 1):
	if l[i] > l[i + 1]:
		k = i + 1
l1 = l[k:] + l[:k]
for i in range(n - 1):
	if l1[i] > l1[i + 1]:
		print(-1)
		break
else:
	print((n - k) % n)


n = int(input())
arr = [int(x) for x in input().split()]
i = 1
temp = sorted(arr)
while i < n and arr[i] >= arr[i - 1]:
	i += 1
if temp == arr[i:] + arr[:i]:
	print((n - i) % n)
else:
	print(-1)


n = int(input())
a = list(map(int, input().split()))
result = 0
flag = False
for i in range(n - 1):
	if a[i + 1] < a[i]:
		result = n - i - 1
		if a[n - 1] > a[0]:
			result = -1
		if flag:
			result = -1
		flag = True
print(result)


n = int(input())
import sys

def get_ints():
	return list(map(int, sys.stdin.readline().strip().split()))
from collections import deque
arr = get_ints()
dicts = {}
flag = 0
maxnum = max(arr)
items = deque(arr)
flag = 0

def checkdecreasing(newarr):
	prev = -1
	for i in newarr:
		if i < prev:
			return False
		prev = i
	return True
ansflag = 0
count = 0
for i in range(n):
	if items[-1] == maxnum:
		flag = 1
		curans = checkdecreasing(items)
		if curans:
			ansflag = 1
			break
	items.rotate(1)
	count += 1
if ansflag:
	print(count)
else:
	print(-1)


def main():
	n = int(input())
	a = list(map(int, input().split()))
	im = 1
	while im < n and a[im] >= a[im - 1]:
		im += 1
	if sorted(a[im:] + a[:im]) == a[im:] + a[:im]:
		print(n - im)
	else:
		print(-1)
main()


n = int(input())
l = list(map(int, input().split()))
if sorted(l) == l:
	print(0)
else:
	k = sorted(l)
	j = 0
	for i in range(1, n):
		if l[i - 1] > l[i]:
			if l[i:] + l[:i] == k:
				print(n - i)
				break
			else:
				print(-1)
				break


import sys
import math as m

def main():
	pass

def binary(n):
	return bin(n).replace('0b', '')

def decimal(s):
	return int(s, 2)

def pow2(n):
	p = 0
	while n > 1:
		n //= 2
		p += 1
	return p

def isPrime(n):
	if n == 1:
		return False
	else:
		root = int(n ** 0.5)
		root += 1
		for i in range(2, root):
			if n % i == 0:
				return False
		return True

def lts(l):
	s = ''.join(map(str, l))
	return s

def stl(s):
	l = list(s)
	return l
mod = int(1000000000.0) + 7

def sinp():
	return sys.stdin.readline().strip()

def iinp():
	return int(input())

def ninp():
	return map(int, sys.stdin.readline().strip().split())

def linp():
	return list(map(int, sys.stdin.readline().strip().split()))

def p(a):
	print(a)

def p2(a, b):
	print(a, b)
n = iinp()
a = linp()
ans = 0
f = 0
for i in range(n - 1):
	if a[i] > a[i + 1]:
		f += 1
		ans = n - i - 1
if f == 0 or (f == 1 and a[0] >= a[-1]):
	print(ans)
else:
	print(-1)


def is_sorted(a):
	for i in range(1, len(a)):
		if a[i - 1] > a[i]:
			return False
	return True

def solve():
	n = int(input())
	a = list(map(int, input().split()))
	if is_sorted(a):
		return 0
	for i in range(1, len(a)):
		if a[i - 1] > a[i]:
			if is_sorted(a[i:] + a[:i]):
				return n - i
			else:
				return -1
print(solve())


n = int(input())
l = [int(i) for i in input().split()]
f = sorted(l)
d = 0
for i in range(n - 1):
	j = i + 1
	if l[j] < l[i]:
		d = i
		break
t = l[0:d + 1]
x = l[d + 1:n]
if l == f:
	print(0)
elif x + t == f:
	print(n - d - 1)
else:
	print(-1)


n = int(input())
l = list(map(int, input().rstrip().split(' ')))
if n == 1:
	print(0)
elif n == 2:
	if l[0] > l[1]:
		print(1)
	else:
		print(0)
else:
	going_down = False
	la = l[0]
	c = 0
	for i in range(1, n):
		if not going_down:
			if l[i] < l[i - 1]:
				going_down = True
				if l[i] > la:
					c = -1
					break
				else:
					c = c + 1
		else:
			if l[i] < l[i - 1] or l[i] > la:
				c = -1
				break
			c += 1
	print(c)


from sys import stdin, stdout
from collections import Counter

def ai():
	return list(map(int, stdin.readline().split()))

def ei():
	return map(int, stdin.readline().split())

def ip():
	return int(stdin.readline().strip())

def op(ans):
	return stdout.write(str(ans) + '\n')
from math import ceil
n = ip()
li = ai()
x = sorted(li)
if x == li:
	exit(print(0))
c = 0
for i in range(n - 1):
	if li[i + 1] < li[i]:
		c = i + 1
ans = li[c:] + li[:c]
for i in range(n - 1):
	if ans[i] > ans[i + 1]:
		print(-1)
		break
else:
	print(n - c)


n = int(input())
l = list(map(int, input().split()))
(f, tp) = (0, 0)
for i in range(1, n):
	if l[i] < l[i - 1]:
		f = 1
		tp = i
		break
if f == 0:
	print(0)
else:
	flg = 0
	tn = 0
	for i in range(tp, n):
		if l[i] <= l[0] and l[i] >= tn:
			tn = l[i]
		else:
			flg = 1
			break
	if flg == 0:
		print(n - tp)
	else:
		print(-1)


import sys, os.path
from collections import *
from copy import *
import math
mod = 10 ** 9 + 7
if os.path.exists('input.txt'):
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
n = int(input())
a = list(map(int, input().split()))
s = deepcopy(a)
s.sort()
c = 0
if a == s:
	print(0)
else:
	res = []
	cnt = 0
	point = 0
	for i in range(1, n - 1):
		if a[i] < a[i - 1] and a[i] <= a[i + 1]:
			point = i
			cnt += 1
			break
	if cnt == 0:
		if a[n - 1] < a[n - 2] and a[n - 1] <= a[0]:
			k = a.pop()
			a = [k] + a
			if s == a:
				print(1)
			else:
				print(-1)
		else:
			print(-1)
	else:
		res = []
		for i in range(point, n):
			res.append(a[i])
		for i in range(point):
			res.append(a[i])
		if res == s:
			print(n - point)
		else:
			print(-1)


n = int(input())
a = list(map(int, input().split()))
l = 0
k = 0
lst = zip(a, a[1:] + [a[0]], range(n))
for (u, v, i) in lst:
	if u > v:
		l += 1
		k = i
if l > 1:
	print(-1)
	quit()
if l == 0:
	print(0)
	quit()
print(n - k - 1)


import sys
import time
import os
from math import sqrt, log, log2, ceil, log10, gcd, floor, pow, sin, cos, tan, pi, inf, factorial
from copy import copy, deepcopy
from sys import exit, stdin, stdout
from collections import Counter, defaultdict, deque
from itertools import permutations
import heapq
from bisect import bisect_left as bl
from bisect import bisect_right as br
from bisect import bisect
mod = 1000000007
iinp = lambda : int(sys.stdin.readline())
inp = lambda : sys.stdin.readline().strip()
strl = lambda : list(inp().strip().split(' '))
intl = lambda : list(map(int, inp().split(' ')))
mint = lambda : map(int, inp().split())
flol = lambda : list(map(float, inp().split(' ')))
flush = lambda : stdout.flush()

def permute(nums):

	def fun(arr, nums, cur, v):
		if len(cur) == len(nums):
			arr.append(cur.copy())
		i = 0
		while i < len(nums):
			if v[i]:
				i += 1
				continue
			else:
				cur.append(nums[i])
				v[i] = 1
				fun(arr, nums, cur, v)
				cur.pop()
				v[i] = 0
				i += 1
		return arr
	res = []
	nums.sort()
	v = [0] * len(nums)
	return fun(res, nums, [], v)

def subsets(res, index, arr, cur):
	res.append(cur.copy())
	for i in range(index, len(arr)):
		cur.append(arr[i])
		subsets(res, i + 1, arr, cur)
		cur.pop()
	return res

def sieve(N):
	root = int(sqrt(N))
	primes = [1] * (N + 1)
	(primes[0], primes[1]) = (0, 0)
	for i in range(2, root + 1):
		if primes[i]:
			for j in range(i * i, N + 1, i):
				primes[j] = 0
	return primes

def bs(arr, l, r, x):
	if x < arr[0] or x > arr[len(arr) - 1]:
		return -1
	while l <= r:
		mid = l + (r - l) // 2
		if arr[mid] == x:
			return mid
		elif arr[mid] < x:
			l = mid + 1
		else:
			r = mid - 1
	return -1

def isPrime(n):
	if n <= 1:
		return False
	if n <= 3:
		return True
	if n % 2 == 0 or n % 3 == 0:
		return False
	p = int(sqrt(n))
	for i in range(5, p + 1, 6):
		if n % i == 0 or n % (i + 2) == 0:
			return False
	return True

def fun(arr, mid, l):
	n = len(arr)
	if mid < arr[0] or mid < l - arr[-1]:
		return False
	for i in range(n - 1):
		if not arr[i] + mid >= arr[i + 1] - mid:
			return False
	return True

def solve():
	n = iinp()
	arr = intl()
	i = 0
	while i < n - 1 and arr[i + 1] >= arr[i]:
		i += 1
	if i == n - 1:
		print(0)
		return
	ans = arr[i + 1:]
	ans.extend(arr[:i + 1])
	if sorted(arr) == ans:
		print(n - i - 1)
	else:
		print(-1)
start_time = time.time()
solve()


n = int(input())
a = list(map(int, input().split()))
lenfirst = 0
cnt = 0
i = 1
while i < len(a):
	if a[i] < a[i - 1]:
		if not cnt:
			lenfirst = i
		cnt += 1
	i += 1
if not cnt:
	print(0)
elif cnt > 1:
	print(-1)
elif a[lenfirst] <= a[0] and a[n - 1] <= a[0]:
	print(n - lenfirst)
else:
	print(-1)


n = int(input())
lis = list(map(int, input().split()))
if lis == sorted(lis):
	print(0)
else:
	for i in range(1, n):
		if lis[i] < lis[i - 1]:
			tmp = lis[i:] + lis[:i]
			if sorted(tmp) == tmp:
				print(n - i)
			else:
				print(-1)
			break


def solve():
	nums = int(input())
	numbers = list(map(int, input().split(' ')))
	if numbers == sorted(numbers):
		print(0)
		return
	highest_index = numbers.index(max(numbers))
	while highest_index < len(numbers) - 1:
		if numbers[highest_index] == numbers[highest_index + 1]:
			highest_index += 1
		else:
			break
	lst1 = numbers[:highest_index + 1]
	lst2 = numbers[highest_index + 1:]
	if lst1 == sorted(lst1) and lst2 == sorted(lst2) and (lst2[-1] <= lst1[0]):
		print(len(lst2))
	else:
		print(-1)
solve()


lens = int(input())
given = [int(x) for x in input().split()]
answer = 0
for i in range(1, lens):
	if given[i] < given[i - 1]:
		if given[i:] + given[:i] == sorted(given):
			answer = lens - i
		else:
			answer = -1
			break
print(answer)


n = int(input())
a = [int(x) for x in input().split()]
ok = True
idx = 0
for i in range(1, n):
	if a[i] < a[i - 1]:
		ok = False
		idx = i
		break
if not ok:
	ok = True
	for i in range(idx, n - 1):
		if a[i] > a[i + 1]:
			ok = False
			break
	if not ok or a[-1] > a[0]:
		print(-1)
	else:
		print(n - idx)
else:
	print(0)


n = int(input())
a = list(map(int, input().split()))
b = list()
c = list()
if a == list(sorted(a)):
	print(0)
	return
for i in range(1, n):
	if a[i] < a[i - 1]:
		b.append(i)
ans = True
if len(b) == 1:
	for i in range(b[0], n):
		c.append(a[i])
	for i in range(b[0]):
		c.append(a[i])
	if c != list(sorted(a)):
		ans = False
if len(b) == 1 and ans:
	print(n - b[0])
else:
	print(-1)


n = int(input())
l = list(map(int, input().split()))
for i in range(n - 1):
	if l[i] > l[i + 1]:
		aux = l[i + 1:] + l[:i + 1]
		l.sort()
		if aux == l:
			print(n - (i + 1))
			exit()
		else:
			print(-1)
			exit()
print(0)


l = int(input())
a = list(map(int, input().split()))
i = 0
while i < l - 1:
	if a[i] > a[i + 1]:
		break
	i += 1
x = a[i + 1:]
x += a[:i + 1]
y = sorted(a)
if x == y:
	print(l - i - 1)
else:
	print(-1)


def us_num(nums):
	where = None
	for (idx, (a, na)) in enumerate(zip(nums[:-1], nums[1:])):
		if a > na:
			if where is None:
				where = idx
			else:
				return -1
	if where is None:
		return 0
	elif nums[-1] > nums[0]:
		return -1
	return len(nums) - 1 - where
n = int(input())
nums = list(map(int, input().split()))
print(us_num(nums))


import sys
import math
n = int(sys.stdin.readline())
an = [int(x) for x in sys.stdin.readline().split()]
t = 0
for i in range(n - 1):
	if an[i] > an[i + 1]:
		t = i + 1
		break
if t == 0:
	print(0)
	exit()
k = an[0]
v = 0
for i in range(n - 1, t - 1, -1):
	if an[i] <= k:
		v += 1
		k = an[i]
	else:
		print(-1)
		exit()
print(v)


from collections import deque, Counter, OrderedDict
from heapq import nsmallest, nlargest
from math import ceil, floor, log, log2, sqrt, gcd, factorial, pow, pi
from bisect import bisect_left, bisect_right

def binNumber(n, size=4):
	return bin(n)[2:].zfill(size)

def iar():
	return list(map(int, input().split()))

def ini():
	return int(input())

def isp():
	return map(int, input().split())

def sti():
	return str(input())

def par(a):
	print(' '.join(list(map(str, a))))

def tdl(outerListSize, innerListSize, defaultValue=0):
	return [[defaultValue] * innerListSize for i in range(outerListSize)]

def sts(s):
	s = list(s)
	s.sort()
	return ''.join(s)

class pair:

	def __init__(self, f, s):
		self.fi = f
		self.se = s

	def __lt__(self, other):
		return (self.fi, self.se) < (other.fi, other.se)
n = ini()
a = iar()
b = []
for i in a:
	b.append(i)
b.sort()
j = 1
while j < n:
	if not a[j] >= a[j - 1]:
		break
	j += 1
if j == n:
	if a == b:
		print(0)
	else:
		print(-1)
	quit()
c = a[j:] + a[:j]
if c == b:
	print(n - j)
else:
	print(-1)


n = int(input())
nums = [int(a) for a in input().split()]
offset = 1
count = 0
while offset < n and nums[offset - 1] <= nums[offset]:
	offset += 1
isOrdered = True
for j in range(offset, n + offset - 1):
	index = j - n if j >= n else j
	nextIndex = j + 1 - n if j + 1 >= n else j + 1
	if nums[index] > nums[nextIndex]:
		isOrdered = False
		break
print(n - offset if isOrdered else -1)


n = int(input())
l = list(map(int, input().split()))
cnt = 0
flag = -1
for i in range(1, n):
	if l[i - 1] > l[i]:
		cnt += 1
		flag = i
if cnt == 0:
	print(0)
elif cnt > 1:
	print(-1)
elif l[0] < l[n - 1]:
	print(-1)
else:
	print(n - flag)


n = int(input())
arr = list(map(int, input().split()))
index = -1
for i in range(n - 1):
	if arr[i + 1] - arr[i] < 0:
		index = i
		break
if index == -1:
	print(0)
else:
	t1 = arr[:index + 1]
	t2 = arr[index + 1:]
	arr = sorted(arr)
	if t2 + t1 == arr:
		print(n - index - 1)
	else:
		print(-1)


num = int(input())
list = list(map(int, input().split()))
counter = 0
for i in range(1, num):
	if list[i] < list[i - 1]:
		list = list[i:] + list[:i]
		counter = 1
		index = i
		break
if list == sorted(list):
	if counter == 0:
		print(0)
	else:
		print(num - index)
else:
	print(-1)


from sys import stdin, stdout
nmbr = lambda : int(stdin.readline())
lst = lambda : list(map(int, stdin.readline().split()))
for _ in range(1):
	n = nmbr()
	a = lst()
	p = -1
	for i in range(1, n):
		if a[i] < a[i - 1]:
			p = i
			break
	if p != -1:
		new = a[p:] + a[:p]
	if p == -1:
		print(0)
	elif new == sorted(a):
		print(n - p)
	else:
		print(-1)


input()
lst = [int(x) for x in input().split()]

def canSort(lst):
	l = 0
	start = -1
	for i in range(len(lst)):
		if l == 0:
			if i > 0:
				if lst[i - 1] > lst[i]:
					l = 1
					start = i
					if lst[start] > lst[0]:
						return -1
		elif l == 1:
			if lst[i - 1] > lst[i] or lst[i] > lst[0]:
				return -1
	return len(lst) - start if start != -1 else 0
print(canSort(lst))


n = int(input())
l = input().split()
for i in range(n):
	l[i] = int(l[i])
k = l.index(min(l))
if k == 0 and l[-1] == l[k]:
	i = n - 1
	while i > -1 and l[i] == l[k]:
		i -= 1
	k = i + 1
j = k
i = j + 1
s = 1
while s < n:
	if i == n:
		i = i % n
	if j == n:
		j = j % n
	if l[j] <= l[i]:
		s += 1
		j += 1
		i += 1
	else:
		break
if s == n:
	if k == 0:
		print(0)
	else:
		print(n - k)
else:
	print(-1)


n = int(input())
a = list(map(int, input().split()))
m = a[0]
mi = 0
dip = False
has_result = True
for i in range(1, n):
	if a[i] >= m and (not dip):
		m = a[i]
		mi = i
	if a[i] < a[i - 1]:
		if dip:
			has_result = False
			break
		else:
			dip = True
	if dip and a[i] > a[0]:
		has_result = False
		break
if has_result:
	print(n - 1 - mi)
else:
	print(-1)


n = int(input())
arr = list(map(int, input().split()))
dip = 0
di = 0
if arr[0] < arr[n - 1]:
	dip += 1
	di = 0
for i in range(1, n):
	if arr[i] < arr[i - 1]:
		dip += 1
		di = i
if dip == 0:
	print(0)
elif dip == 1:
	if di == 0:
		print(0)
	else:
		print(n - di)
else:
	print(-1)


n = int(input())
l = list(map(int, input().split()))
l2 = []
m = l[0]
k = l[0]
for i in range(1, n):
	if l[i] >= k:
		k = l[i]
	else:
		l2 = l[i:]
		break
c = 0
ans = 0
if len(l2) > 0:
	k2 = l2[0]
	if m >= k2:
		ans = 1
	else:
		ans = -1
for i in range(1, len(l2)):
	if k2 > l2[i] or l2[i] > m:
		ans = -1
		break
	else:
		ans += 1
		k2 = l2[i]
if ans == -1:
	print('-1')
else:
	print(ans)


def helper(arr, n, i):
	start = n - 1
	end = -1
	flag = 0
	index = n - 1
	for j in range(i + 1, n):
		if arr[j] < arr[j - 1]:
			return -1
	if arr[n - 1] > arr[0]:
		return -1
	return n - i
n = int(input())
arr = list(map(int, input().split()))
flag = 0
index = -1
for i in range(1, n):
	if arr[i] < arr[i - 1]:
		index = i
		flag = 1
		break
if flag == 0:
	print(0)
else:
	print(helper(arr, n, index))


from collections import deque
n = int(input())
l = [int(x) for x in input().split()]
flag = 0
index = -1
for i in range(len(l) - 1):
	if l[i + 1] < l[i]:
		index = i + 1
		break
if index == -1:
	print(0)
elif index == len(l) - 1:
	if l[index] <= l[0]:
		print(1)
	else:
		print(-1)
else:
	count = 0
	for i in range(index, len(l) - 1):
		if l[i + 1] >= l[i] and l[i] <= l[0] and (l[len(l) - 1] <= l[0]):
			count += 1
		else:
			flag = 1
			break
	if flag == 0:
		print(count + 1)
	else:
		print(-1)


n = int(input())
a = list(map(int, input().split()))
l = []
for i in range(1, n):
	l.append(a[i] - a[i - 1])
l.append(a[0] - a[-1])
c = 0
for i in range(n):
	if l[i] < 0:
		c += 1
		ind = i
if c == 0:
	print(0)
elif c > 1:
	print('-1')
else:
	print(n - ind - 1)


n = int(input())
l = [int(y) for y in input().split()]
if n == 1:
	print(0)
elif n == 2:
	if l[0] <= l[1]:
		print(0)
	else:
		print(1)
else:
	i = 0
	while i < n - 1:
		if l[i] <= l[i + 1]:
			i += 1
		else:
			break
	if i == n - 1:
		print(0)
	else:
		c = 0
		check = 0
		j = i + 1
		while j < n - 1:
			if l[j] <= l[j + 1] and l[j] <= l[0]:
				c += 1
				j += 1
			else:
				check = 1
				break
		if l[n - 1] <= l[0]:
			c += 1
			if check == 1:
				print(-1)
			else:
				print(c)
		else:
			print(-1)


import sys
from functools import lru_cache, cmp_to_key
from heapq import merge, heapify, heappop, heappush
from collections import defaultdict as dd, deque, Counter as C
from itertools import combinations as comb, permutations as perm
from bisect import bisect_left as bl, bisect_right as br, bisect
from time import perf_counter
from fractions import Fraction
import copy
import time
starttime = time.time()
mod = int(pow(10, 9) + 7)
mod2 = 998244353

def data():
	return sys.stdin.readline().strip()

def out(*var, end='\n'):
	sys.stdout.write(' '.join(map(str, var)) + end)

def L():
	return list(sp())

def sl():
	return list(ssp())

def sp():
	return map(int, data().split())

def ssp():
	return map(str, data().split())

def l1d(n, val=0):
	return [val for i in range(n)]

def l2d(n, m, val=0):
	return [l1d(n, val) for j in range(m)]
try:
	sys.stdin = open('input.txt', 'r')
except:
	pass
n = L()[0]
A = L()
if A == sorted(A):
	print(0)
	exit()
for i in range(n - 1):
	if A[i] > A[i + 1]:
		break
B = A[i + 1:] + A[:i + 1]
if B == sorted(B):
	print(n - i - 1)
else:
	B = [A[-1]] + A[:-1]
	if B == sorted(B):
		print(1)
	else:
		print(-1)
endtime = time.time()


def main():
	n = int(input())
	l = list(map(int, input().split()))
	a = l[0]
	for (i, b) in enumerate(l):
		if a > b:
			l = l[i:] + l[:i]
			i = n - i
			break
		a = b
	else:
		i = 0
	print(i if l == sorted(l) else -1)
main()


import sys
n = int(sys.stdin.readline())
ok = True
inc = True
(last, res, i) = (0, 0, 0)
first = 0
for num in sys.stdin.readline().split():
	num = int(num)
	if first == 0:
		first = num
	if last > num:
		if inc:
			inc = False
			res = n - i
		else:
			ok = False
	last = num
	i = i + 1
if last > first:
	if inc:
		pass
	else:
		ok = False
if ok:
	print(res)
else:
	print(-1)


n = int(input())
arr = list(map(int, input().split()))
start = 0
for i in range(n - 1):
	if arr[i] > arr[i + 1]:
		start = i + 1
arr = arr[start:] + arr[:start]
for i in range(n - 1):
	if arr[i] > arr[i + 1]:
		print(-1)
		exit(0)
else:
	print((n - start) % n)


n = int(input())
a = list(map(int, input().split()))
l = sorted(a)
c = 0
for i in range(n - 1):
	if a[i] > a[i + 1]:
		if a[i + 1:n] + a[0:i + 1] == l:
			c = len(a[i + 1:n])
		break
if a == l:
	print(c)
elif c != 0:
	print(c)
elif c == 0:
	print(-1)


n = int(input())
inp = list(map(int, input().split()))
flag = 0
for i in range(n - 1):
	if inp[i + 1] < inp[i]:
		ind = i + 1
		flag += 1
		break
if flag == 1:
	for i in range(n - 1):
		if inp[(i + 1 + ind) % n] < inp[(i + ind) % n]:
			flag += 1
			break
if flag == 0:
	print(0)
elif flag == 1:
	print((n - ind) % n)
else:
	print(-1)


n = int(input())
a = list(map(int, input().split()))
cnt = 0
yep = 0
for i in range(1, n):
	if a[i - 1] > a[i]:
		cnt += 1
		yep = i
if cnt == 0:
	print(0)
elif cnt > 1:
	print(-1)
elif a[0] < a[n - 1]:
	print(-1)
else:
	print(n - yep)


n = eval(input())
a = list(map(int, input().split()))
pre = a[0]
pos = n
for i in range(1, n):
	x = a[i]
	if x < pre:
		pre = x
		pos = i
		break
	pre = x
if pos == n:
	print(0)
else:
	ans = 0
	for j in range(pos, n):
		x = a[j]
		if x < pre:
			ans = -1
			break
		pre = x
	if ans == -1:
		print(-1)
	elif a[n - 1] > a[0]:
		print(-1)
	else:
		print(n - pos)


n = int(input())
x = list(map(int, input().split()))
for i in range(1, n):
	if x[i - 1] > x[i]:
		if sorted(x) == x[i:] + x[:i]:
			print(n - i)
			exit()
		else:
			print(-1)
			exit()
print(0)


n = int(input())
array = list(map(int, input().split()))
i = 0
while i < n - 1 and array[i] <= array[i + 1]:
	i += 1
if i == n - 1:
	print(0)
elif array[i + 1:] == sorted(array[i + 1:]) and array[-1] <= array[0]:
	print(n - i - 1)
else:
	print(-1)


n = int(input())
l = list(map(int, input().split()))
d = 0
r = 0
for i in range(n - 1):
	if l[i + 1] < l[i]:
		d = i + 1
		break
l = l[d:] + l[:d]
r = n - d
if l == sorted(l):
	print(r % n)
else:
	print(-1)


def main():
	n = int(input())
	a = list(map(int, input().split()))
	a.append(a[0])
	p = -1
	cnt = 0
	for i in range(n):
		if a[i] > a[i + 1]:
			p = i
			cnt += 1
			if cnt > 1:
				print(-1)
				return
	print(cnt * (n - p - 1))
main()


input()
xs = [int(x) for x in input().split()]

def solve(xs):
	divide = 0
	cnt = 0
	for i in range(1, len(xs)):
		if xs[i] < xs[i - 1]:
			cnt += 1
			if cnt == 2:
				return -1
			divide = i
	if divide != 0 and xs[0] < xs[len(xs) - 1]:
		return -1
	if divide == 0:
		return 0
	return len(xs) - divide
print(solve(xs))


import os
import sys
from math import *
from collections import *
from fractions import *
from bisect import *
from heapq import *
from io import BytesIO, IOBase

def vsInput():
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
ALPHA = 'abcdefghijklmnopqrstuvwxyz'
M = 1000000007

def value():
	return tuple(map(int, input().split()))

def array():
	return [int(i) for i in input().split()]

def Int():
	return int(input())

def Str():
	return input()

def arrayS():
	return [i for i in input().split()]
n = Int()
a = array()
wrong = -1
ok = True
for i in range(n):
	if a[i] < a[i - 1]:
		if wrong != -1:
			ok = False
		wrong = i
if ok:
	if wrong == -1:
		wrong = 0
	print((n - wrong) % n)
else:
	print(-1)


n = int(input())
num = [int(x) for x in input().split()]
for i in range(0, n):
	if num[i] < num[i - 1]:
		p = num[i:]
		q = num[:i]
		break
d = sorted(num)
if num == d:
	print('0')
elif d == p + q:
	print(len(p))
else:
	print('-1')


n = int(input())
a = [int(i) for i in input().split()]
out = 0
inc_ord = True
for i in range(n - 1):
	if inc_ord:
		if a[i] > a[i + 1]:
			inc_ord = False
			out = i + 1
			if a[i + 1] > a[0]:
				out = -1
				break
	elif a[i + 1] > a[0] or a[i] > a[i + 1]:
		out = -1
		break
if out <= 0:
	print(out)
else:
	print(n - out)


def solve():
	n = int(input())
	arr = [int(i) for i in input().split()]
	(idx, cnt) = (0, 0)
	for i in range(n - 1):
		if arr[i] > arr[i + 1]:
			cnt += 1
			idx = i + 1
	if cnt == 0:
		print(0)
	elif cnt == 1 and arr[n - 1] <= arr[0]:
		print(n - idx)
	else:
		print(-1)
solve()


n = int(input())
a = [int(x) for x in input().split()]
count = 0
i = 1
flag = 0
while i < n:
	if a[i - 1] <= a[i]:
		i = i + 1
	else:
		flag = 1
		break
if flag == 1:
	if a[i - 1] > a[i] and a[i] <= a[0]:
		count = count + 1
		i = i + 1
	else:
		flag = 2
if flag == 1:
	while i < n:
		if a[i - 1] <= a[i] and a[i] <= a[0]:
			count = count + 1
			i = i + 1
		else:
			flag = 2
			break
if flag == 2:
	print(-1)
else:
	print(count)


def naek(a, indeks):
	for x in range(indeks, len(a) - 1):
		if a[x] > a[x + 1]:
			return False
			pass
		pass
		pass
	return True
	pass
dum = 0
a = int(input())
a = list(map(int, input().split(' ')))
sor = True
for x in range(len(a) - 1):
	if a[x] > a[x + 1]:
		sor = False
		idx = x + 1
		break
		pass
	pass
if sor:
	print(0)
else:
	if naek(a, idx):
		if a[len(a) - 1] > a[0]:
			print(-1)
		else:
			print(len(a) - idx)
			pass
		pass
	else:
		print(-1)
	pass


n = int(input())
ls = list(map(int, input().split()))
if ls == sorted(ls):
	print(0)
elif ls == sorted(ls, reverse=True):
	if n == 2:
		print(1)
	else:
		print(-1)
else:
	counter = 0
	b = False
	for i in range(1, n):
		if i == n - 1 and ls[-1] > ls[0]:
			counter = -1
			break
		if ls[i] < ls[i - 1] and (not b):
			counter += 1
			b = True
		elif not b and ls[i] < ls[i - 1]:
			counter = -1
			break
		elif b:
			if ls[i] >= ls[i - 1]:
				counter += 1
			else:
				counter = -1
				break
	print(counter)


n = int(input())
lst = list(map(int, input().split()))
ans = 0
for i in range(1, n):
	if lst[i] < lst[i - 1]:
		ans = i
		break
for i in range(ans + 1, n):
	if lst[i] < lst[i - 1]:
		ans = -1
		break
if ans == 0:
	print(0)
elif ans != -1 and lst[-1] <= lst[0]:
	print(n - ans)
else:
	print(-1)


n = int(input())
lst = list(map(int, input().split()))
for i in range(1, n):
	if lst[i - 1] > lst[i]:
		print([-1, n - i][sorted(lst) == lst[i:] + lst[:i]])
		exit()
print(0)


import sys
n = int(input())
l1 = list(map(int, input().split()))
l3 = l1.copy()
l3.sort()
for i in range(1, n):
	if l1[i - 1] > l1[i]:
		l2 = l1[i:] + l1[:i]
		if l3 == l2:
			print(n - i)
			sys.exit()
		else:
			print(-1)
			sys.exit()
print(0)


def main():
	n = int(input())
	lst = list(map(int, input().split()))
	ispeak = 0
	indexx = -1
	for i in range(1, n):
		if lst[i] < lst[i - 1]:
			ispeak += 1
			if ispeak == 1:
				indexx = i
	if ispeak == 0:
		print(0)
	elif ispeak != 1:
		print(-1)
	elif lst[0] >= lst[n - 1]:
		print(n - indexx)
	else:
		print(-1)
t = 1
while t != 0:
	main()
	t -= 1


def pony(arr):
	cont = 0
	bandera = False
	a = len(arr)
	for i in range(0, a - 1):
		if arr[i] <= arr[i + 1] and bandera == False:
			continue
		elif arr[i] <= arr[i + 1] and bandera == True:
			cont = cont + 1
		elif arr[i] > arr[i + 1]:
			bandera = True
			cont = cont + 1
			if cont >= 2:
				return -1
	if arr[0] < arr[-1] and bandera == True:
		return -1
	return cont
n = int(input())
arr1 = list(map(int, input().strip().split()))
print(pony(arr1))


n = int(input())
a = list(map(int, input().split()))
b = sorted(a)
if a == b:
	print(0)
	exit()
ans_idx = -1
for i in range(n - 2, -1, -1):
	if a[i] > a[i + 1]:
		ans_idx = i
		break
if ans_idx == -1:
	print(-1)
	exit()
c = a[ans_idx + 1:] + a[:ans_idx + 1]
if c == b:
	print(n - 1 - ans_idx)
else:
	print(-1)


n = int(input())
a = [int(v) for v in input().strip().split()]
for i in range(n - 1):
	if a[i] > a[i + 1]:
		if sorted(a) == a[i + 1:] + a[:i + 1]:
			print(n - i - 1)
		else:
			print(-1)
		exit(0)
print(0)


def shift(arr):
	k = arr[-1]
	n = len(arr)
	for i in range(n - 1):
		arr[n - 1 - i] = arr[n - 1 - i - 1]
	arr[0] = k

def proB(arr):
	c = 0
	s = 0
	n = len(arr)
	for i in range(len(arr) - 1):
		if arr[i] > arr[i + 1]:
			s = i + 1
			c += 1
	if c == 0:
		print(0)
		return
	if arr[0] < arr[-1]:
		c += 1
	if c >= 2:
		print(-1)
	else:
		print(n - s)
n = int(input())
arr = list(map(int, input().split()))
proB(arr)


n = int(input())
a = list(map(int, input().split()))
i = 1
while i < n and a[i - 1] <= a[i]:
	i += 1
if i == n:
	print(0)
else:
	j = i + 1
	while j < n and a[j - 1] <= a[j]:
		j += 1
	if j < n or a[-1] > a[0]:
		print(-1)
	else:
		print(j - i)


n = int(input())
a = list(map(int, input().strip().split()))
t = 0
b = 0
for i in range(1, n):
	if a[i] < a[i - 1]:
		t += 1
		b = i
if t == 0:
	print(0)
elif t == 1 and a[n - 1] <= a[0]:
	print(n - b)
else:
	print(-1)


import sys
n = int(input())
a = list(map(int, sys.stdin.readline().split()))
ans = -1
for i in range(n - 1):
	if a[i] > a[i + 1]:
		ans = i
		break
if ans == -1:
	print(0)
else:
	for i in range(ans + 1, n - 1):
		if a[i] > a[i + 1]:
			print(-1)
			break
	else:
		if a[-1] <= a[0]:
			print(n - ans - 1)
		else:
			print(-1)


n = int(input())
arr = list(map(int, input().rstrip().split(' ')))
idx = n - arr[::-1].index(min(arr)) - 1
if len(arr) == 1:
	print(0)
else:
	change = 0
	idxChange = None
	for i in range(n):
		if arr[i] > arr[(i + 1) % n]:
			change += 1
			idxChange = i
		if change >= 2:
			print(-1)
			break
	else:
		if idxChange is not None:
			print(n - 1 - idxChange)
		else:
			print(0)


n = int(input())
a = [int(i) for i in input().split()]
for i in range(n):
	if i < n - 1 and a[i + 1] < a[i]:
		break
if i == n - 1:
	ans = 0
else:
	ans = n - 1 - i
a = a[i + 1:] + a[:i + 1]
for i in range(n - 1):
	if a[i] > a[i + 1]:
		print(-1)
		break
else:
	print(ans)


n = int(input())
numbers = list(map(int, input().split()))
smallerBefore = numbers[0]
graterAfter = 0
fallIndex = -2
for i in range(0, n):
	if fallIndex > -1:
		if numbers[i] > numbers[fallIndex]:
			fallIndex = -1
			break
		if numbers[i] > graterAfter:
			graterAfter = numbers[i]
	elif numbers[i] < smallerBefore:
		smallerBefore = numbers[i]
	if i < n - 1 and numbers[i] > numbers[i + 1]:
		if fallIndex > -1:
			fallIndex = -1
			break
		fallIndex = i
		graterAfter = numbers[i + 1]
		continue
	if i == n - 1 and fallIndex > -1 and (smallerBefore < graterAfter):
		fallIndex = -1
		break
print(-1 if fallIndex == -1 else 0 if fallIndex == -2 else n - fallIndex - 1)


n = input()
n = int(n)
d = [int(x) for x in input().split(' ')]
e = 0
f = 0
for i in range(1, n):
	if d[i - 1] <= d[i]:
		if f == 0 or (f == 1 and d[i] <= d[0]):
			pass
		else:
			e = -1
			break
	elif f == 0 and d[0] >= d[i]:
		f = 1
		e = i
	else:
		e = -1
		break
if e == -1:
	print(-1)
else:
	print((n - e) % n)


inp = lambda : map(int, input().split())
n = int(input())
a = list(inp())
p = 0
for i in range(n - 1):
	if a[i] > a[i + 1]:
		p = i + 1
b = a[p:] + a[:p]
flag = True
for i in range(n - 1):
	if b[i] > b[i + 1]:
		flag = False
		break
print((n - p) % n if flag else -1)


def main():
	n = int(input())
	l = input().split()
	l.append(l[0])
	cnt = idx = a = 0
	for (i, b) in enumerate(l):
		b = int(b)
		if a > b:
			if cnt:
				print(-1)
				return
			cnt += 1
			idx = n - i
		a = b
	print(idx)
main()


from sys import *
from math import *
from sys import stdin, stdout
from collections import *
int_arr = lambda : list(map(int, stdin.readline().strip().split()))
str_arr = lambda : list(map(str, stdin.readline().split()))
get_str = lambda : map(str, stdin.readline().strip().split())
get_int = lambda : map(int, stdin.readline().strip().split())
get_float = lambda : map(float, stdin.readline().strip().split())
mod = 1000000007
setrecursionlimit(1000)
n = int(input())
arr = int_arr()
mn = min(arr)
lst = arr.copy()
lst.sort()
if arr == lst:
	print(0)
else:
	mx = -1
	for i in range(len(arr)):
		if arr[i] >= mx:
			mx = arr[i]
		else:
			ele = arr[i]
			ind = i
			break
	if ele == mn:
		arr = arr[ind:] + arr[:ind]
		if arr == lst:
			print(n - ind)
		else:
			print(-1)
	else:
		print(-1)


n = int(input())
li = list(map(int, input().split(' ')))
sli = list(sorted(li))
i = 0
start = li.index(li[0])
checker = False
while i < n:
	if li[i] == sli[0]:
		if checker == False:
			start = i
			checker = True
	else:
		checker = False
	i += 1
i = start
res = n - start
if res == n:
	res = 0
for x in sli:
	if li[i % n] != x:
		res = -1
		break
	i += 1
print(res)


an = 0
n = int(input())
a = [int(x) for x in input().split()]
p = 0
for i in range(1, n):
	if p == 0:
		if a[i] < a[i - 1]:
			p = 1
			an = i
			if a[i] > a[0]:
				p = 2
	else:
		if a[i] > a[0]:
			p = 2
		if a[i] < a[i - 1]:
			p = 2
if p == 2:
	print(-1)
elif an != 0:
	print(n - an)
else:
	print(an)


n = int(input())
arr = list(map(int, input().split()))
start = 0
check = 0
for i in range(1, n):
	if arr[i] < arr[i - 1]:
		start = i
		break
if start == 0:
	print(0)
elif start == n - 1 and arr[-1] <= arr[0]:
	print(1)
elif arr[-1] <= arr[0]:
	for j in range(start + 1, n):
		if arr[j] < arr[j - 1]:
			check = 1
			break
	if check == 1:
		print(-1)
	else:
		print(n - start)
else:
	print(-1)


n = int(input())
a = [int(x) for x in input().split()]
b = max(a)
for i in range(n):
	if a[i] == b and (i == n - 1 or a[i + 1] < b):
		x = i
		break
if a[x + 1:n] + a[0:x + 1] == sorted(a):
	print(n - 1 - x)
else:
	print(-1)


a = int(input())
b = list(map(int, input().split()))
c = b.copy()
c.sort()
if b == c:
	print(0)
else:
	for i in range(1, len(b)):
		if b[i] < b[i - 1]:
			k = i
			break
	q = b[k:] + b[:k]
	if c == q:
		print(a - k)
	else:
		print(-1)


n = int(input())
arr = list(map(int, input().split()))
idx = -1
for (i, x) in enumerate(arr):
	if i == 0:
		continue
	if arr[i] < arr[i - 1]:
		idx = i
		break
if idx == -1:
	print(0)
else:
	b = arr[idx:] + arr[:idx]
	if sorted(b) == b:
		print(n - i)
	else:
		print(-1)


n = int(input())
l = [int(x) for x in input().split()]
i = 0
pos = 0
flag = 1
for i in range(n - 1):
	if l[i] > l[i + 1]:
		pos = i + 1
		for j in range(i + 1, n - 1):
			if l[j] > l[j + 1]:
				flag = 0
				break
		break
if pos == 0:
	print(pos)
elif flag and l[-1] <= l[0]:
	print(n - pos)
else:
	print(-1)


n = int(input())
l = list(map(int, input().split()))
count = 0
for i in range(n):
	if l[i] < l[i - 1]:
		count += 1
l2 = sorted(l)
if l == l2:
	print(0)
elif count > 1 or l[n - 1] > l[0]:
	print(-1)
else:
	for i in range(n):
		if l[i] > l[i + 1]:
			print(n - i - 1)
			break


n = int(input())
l_i = list(map(int, input().split()))
m_i = l_i.index(min(l_i))
p = l_i[m_i]
m_m = False
n_m_i = -1
for i in range(1, n):
	if not m_m and l_i[(m_i + i) % n] >= p:
		p = l_i[(m_i + i) % n]
	elif l_i[(m_i + i) % n] == l_i[m_i]:
		if not m_m:
			m_m = True
			n_m_i = (m_i + i) % n
	else:
		print(-1)
		quit()
if n_m_i != -1:
	m_i = n_m_i
print((n - m_i) % n)


n = int(input())
string = input()
numbers = list(map(int, string.split()))
order = ' '.join(map(str, sorted(numbers)))[::-1]
string = ' '.join(map(str, numbers))
string = '%s %s' % (string, string)
string = string[::-1]
if order in string:
	a = string.index(order)
	print(string[:a].count(' '))
else:
	print(-1)


I = lambda : list(map(int, input().split()))
n = int(input())
a = I()
sa = sorted(a)
a = a + a
s = 0
for i in range(1, n * 2):
	if a[i] < a[i - 1]:
		s = 0
	else:
		s += 1
		if s == n - 1:
			break
print((-i - 1) % n if s == n - 1 else -1)


n = int(input())
a = list(map(int, input().split()))
a.reverse()
aa = a + a
r = 1
l = 0
ans = -1
while r < 2 * n:
	while r < 2 * n:
		if aa[r - 1] < aa[r]:
			break
		r += 1
	if r - l >= n:
		ans = l
		break
	l = r
	r += 1
print(ans)


def f(A):
	(lo, hi) = (0, len(A) - 1)
	while lo < hi:
		mid = lo + (hi - lo) // 2
		if A[mid] <= A[hi]:
			hi = mid
		else:
			lo = mid + 1
	assert lo == hi
	return lo
assert f([1, 2, 3, 4]) == 0
assert f([4, 1, 2, 3]) == 1
assert f([3, 4, 1, 2]) == 2
assert f([1, 3, 2]) == 2
assert f([2, 3, 4, 5, 6, 7, 8, 9, 10, 1]) == 9
assert f([99997, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]) == 1
assert f([1, 1, 1, 1, 1]) == 0
assert f([1, 1, 1, 1, 2, 0]) == 5
assert f([2, 3, 4, 1, 2]) == 3
assert f([5, 5, 5, 5, 3, 3, 3, 3, 4, 5]) == 4
assert f([5, 5, 5, 5, 5, 5, 5, 5, 3, 5, 5]) == 0
n = int(input())
A = list(map(int, input().split()))
ans = 0
for i in range(1, len(A)):
	if A[i - 1] > A[i]:
		ans = i
		break
if ans >= 0:
	for i in range(ans + 1, len(A)):
		if A[i - 1] > A[i]:
			ans = -1
			break
if ans > 0:
	if A[-1] > A[0]:
		ans = -1
if ans > 0:
	print(len(A) - ans)
else:
	print(ans)


n = int(input())
lis = list(map(int, input().split()))
flag = 0
i = -1
for j in range(1, n):
	if flag == 0 and lis[j] < lis[j - 1]:
		flag = 1
		i = n - j
		continue
	if flag == 1 and lis[j] < lis[j - 1]:
		flag = 2
		break
if flag == 1 and lis[0] < lis[n - 1]:
	flag = 2
if flag == 0:
	print(0)
elif flag == 1:
	print(i)
else:
	print(-1)


N = int(input())
r = input()
li = []
flag = 0
for x in r.split():
	li.append(int(x))
if li == sorted(li):
	print('0')
	flag = 1
l = 0
for i in range(N - 1):
	if li[i] > li[i + 1]:
		n = i
		l += 1
		if l == 2:
			print('-1')
			flag = 1
			break
if flag == 0:
	if li[0] >= li[N - 1]:
		print(N - n - 1)
	else:
		print('-1')


n = int(input())
ai = list(map(int, input().split()))
miss = 0
miss_num = n - 1
for i in range(n - 1):
	if ai[i + 1] < ai[i]:
		miss_num = i
		miss += 1
if ai[-1] > ai[0]:
	miss_num = n - 1
	miss += 1
if miss > 1:
	print(-1)
else:
	print(n - miss_num - 1)


n = int(input())
pos = list(map(int, input().split()))
x = pos[0]
i = 1
while i != n and pos[i] >= pos[i - 1]:
	i += 1
k = 0
ans = n - i
for j in range(i + 1, n):
	if pos[j] < pos[j - 1]:
		k = 1
		break
if pos[n - 1] > pos[0] and ans != 0:
	k = 1
if k == 1:
	print(-1)
else:
	print(ans)


n = int(input())
l = list(map(int, input().split()))
max = -1
k = 0
flag = 1
index = 0
for i in range(len(l)):
	if l[(k + 1) % n] < l[k]:
		if max != -1:
			flag = 0
			print(-1)
			break
		else:
			max = l[k]
			index = (k + 1) % n
	k = (k + 1) % n
if flag == 1:
	if index != 0:
		print(n - index)
	else:
		print(0)


def main():
	num = input()
	arr = input().split(' ')
	arr_ = [int(i) for i in arr]
	if len(arr_) == 0:
		return -1
	breakpoint = 0
	sol = 0
	for i in range(len(arr_) - 1):
		if arr_[i + 1] >= arr_[i]:
			breakpoint += 1
		else:
			break
	if arr_[-1] > arr_[0] and breakpoint != len(arr) - 1:
		print(-1)
		return
	for i in range(breakpoint + 1, len(arr_) - 1):
		sol += 1
		if arr_[i + 1] < arr_[i]:
			print(-1)
			return
	print(len(arr_) - 1 - breakpoint)
main()


n = int(input())
nums = list(map(int, input().split()))
first = 0
for i in range(0, n - 1):
	if nums[i] > nums[i + 1]:
		first = i + 1
nums = nums[first:] + nums[:first]
flag = True
for i in range(n - 1):
	if nums[i] > nums[i + 1]:
		flag = False
if flag:
	print((n - first) % n)
else:
	print(-1)


n = int(input())
a = list(map(int, input().split()))
sub = []
for i in range(1, n):
	x = a[i] - a[i - 1]
	sub.append(x)
sub.append(a[0] - a[-1])
c = 0
for i in range(n):
	if sub[i] < 0:
		c += 1
		pos = i
if c == 0:
	print(0)
elif c > 1:
	print(-1)
else:
	print(n - pos - 1)


n = int(input())
l = list(map(int, input().split()))
count = 0
temp = l.copy()
temp.sort()
if temp == l:
	print(0)
	quit()
for i in range(1, n):
	if l[i] < l[i - 1]:
		count += 1
		ans = n - i
if count == 1 and l[0] >= l[-1] or count == 0:
	print(ans)
else:
	print(-1)


import math

def findCol(a, n):
	mn = 1234567890
	id = 0
	k = []
	for i in range(1, n):
		if a[i] <= a[id] and a[i] != a[i - 1]:
			id = i
	for i in range(id, n):
		k.append(a[i])
	for i in range(id):
		k.append(a[i])
	a.sort()
	if a != k:
		return -1
	elif id == 0:
		return 0
	else:
		return n - id
n = int(input())
a = list(map(int, input().split()))
print(findCol(a, n))


t = int(input())
a = list(map(int, input().split()))
e = 0
for i in range(1, t):
	if a[i - 1] > a[i]:
		if sorted(a) == a[i:] + a[:i]:
			print(t - i)
			e = 1
			break
		else:
			print(-1)
			e = 1
			break
if e == 0:
	print(0)


a = int(input())
k = list(map(int, input().split()))
l = sorted(k)
c = 0
for i in range(1, a):
	if k[i - 1] > k[i]:
		c += 1
if k == l:
	print(0)
elif c > 1 or k[-1] > k[0]:
	print(-1)
else:
	for i in range(1, len(k)):
		if k[i - 1] > k[i]:
			print(a - i)


import sys

def fastio():
	from io import StringIO
	from atexit import register
	global input
	sys.stdin = StringIO(sys.stdin.read())
	input = lambda : sys.stdin.readline().rstrip('\r\n')
	sys.stdout = StringIO()
	register(lambda : sys.__stdout__.write(sys.stdout.getvalue()))
fastio()

def debug(*var, sep=' ', end='\n'):
	print(*var, file=sys.stderr, end=end, sep=sep)
INF = 10 ** 20
MOD = 10 ** 9 + 7
I = lambda : list(map(int, input().split()))
from math import gcd
from math import ceil
from collections import defaultdict as dd, Counter
from bisect import bisect_left as bl, bisect_right as br
(n,) = I()
a = I()
m = min(a)
f = 0
idx = 0
for i in range(1, n):
	if a[i - 1] > a[i]:
		idx = i
		break
ans = INF
a = a[idx:] + a[:idx]
ans = min(ans, n - idx)
if a != sorted(a):
	print(-1)
	exit()
print(ans % n)


z = int(input())
x = list(map(int, input().split()))
d = sorted(x)
if d == x:
	print(0)
	exit()
w = x.copy()
f = w[-1]
w.pop(-1)
w.insert(0, f)
if w == d:
	print(1)
	exit()
t = True
c = 0
e = x.copy()
for i in range(1, z - 1):
	if x[i] != d[i - 1]:
		t = False
		break
if x[-1] > x[0]:
	t = False
for i in range(1, z):
	if i != z - 1:
		t = False
		if x[i] <= x[0] and x[i - 1] != x[i]:
			break
	elif x[i] <= x[0]:
		t = False
		break
a = x[:i]
b = x[i:]
if b + a == d:
	print(len(b))
elif t:
	print(z - 1)
else:
	print(-1)


n = int(input())
ara = list(map(int, input().strip().split()))
ara2 = ara
ara = sorted(ara)
if ara2 == ara:
	print('0')
else:
	pos = 0
	count = 0
	for i in range(n):
		if i != n - 1 and ara2[i] > ara2[i + 1]:
			count += 1
			pos = i
		elif i == n - 1 and ara2[i] > ara2[0]:
			count += 1
			pos = i
	if count > 1:
		print(-1)
	else:
		print(n - 1 - pos)


a = int(input())
b = list(map(int, input().split(' ')))
x = 0
y = 0
for i in range(len(b) - 1):
	if b[i] > b[i + 1]:
		x = i
		y = y + 1
if b[a - 1] > b[0]:
	x = a - 1
	y = y + 1
if y == 0:
	print(0)
elif y > 1:
	print(-1)
else:
	print(a - x - 1)


n = int(input())
l = list(map(int, input().split()))
l1 = []
l2 = []
l3 = []
p = -1
k = 0
c = 0
t = 0
for i in range(n - 1):
	if l[i] > l[i + 1]:
		p = i
		c = 1
		l1.append(l[i])
		break
	else:
		l1.append(l[i])
if p != -1:
	for j in range(p + 1, n):
		l2.append(l[j])
		k = k + 1
else:
	l1.append(l[n - 1])
if l2 + l1 == sorted(l) or k == 0:
	print(k)
else:
	print(-1)


n = int(input())
l = list(map(int, input().split()))
if n == 2:
	if l[1] >= l[0]:
		print(0)
	else:
		print(1)
elif l[n - 1] > l[0]:
	print(-1)
else:
	x = 0
	h = -1
	for q in range(n - 2, -1, -1):
		if l[q + 1] < l[q]:
			x += 1
			h = n - q - 1
	if x > 1:
		print(-1)
	elif x == 0:
		print(0)
	else:
		print(h)


n = int(input())
list1 = list(map(int, input().split()))
list2 = []
f = 0
ii = 0
for i in range(n - 1):
	if list1[i] <= list1[i + 1]:
		continue
	else:
		f += 1
		ii = i + 1
if f == 1 and list1[ii] <= list1[0] and (list1[-1] <= list1[0]):
	print(n - ii)
elif f == 0:
	print(0)
else:
	print(-1)


import sys
n = int(input())
l = [int(x) for x in input().split()]
count = 0
li = 0
for i in range(n - 1):
	if l[i] > l[i + 1]:
		count += 1
		li = i
if count == 0:
	print(0)
	sys.exit()
if count == 1 and l[n - 1] <= l[0]:
	print(n - 1 - li)
else:
	print(-1)


x = int(input())
s = list(map(int, input().split()))
z = sorted(s)
a = -1
for n in range(x - 1):
	if s[n] > s[n + 1]:
		a = n
		break
if a == -1:
	print(0)
	exit(0)
for n in range(a + 1, x):
	if s[n] != z[n - a - 1]:
		print(-1)
		exit(0)
print(x - a - 1)


n = int(input())
arr = list(map(int, input().split()))
flag = -1
f = 0
for i in range(0, n - 1):
	if arr[i] > arr[i + 1]:
		flag = i + 1
		break
temp = list(range(flag, n)) + list(range(0, flag))
for i in range(0, n - 1):
	if arr[temp[i]] > arr[temp[i + 1]]:
		f = 1
		break
if flag == -1:
	print(0)
elif f == 0:
	print(n - flag)
else:
	print(-1)


n = int(input())
line = list(map(int, input().split()))
p = 0
f = True
for i in range(n):
	if line[i] > line[(i + 1) % n]:
		if f:
			p = n - 1 - i
			f = False
		else:
			p = -1
			break
print(p)


n = int(input())
a = list(map(int, input().split()))
s = a.copy()
s.sort()
ind = 0
if s[0] == s[n - 1]:
	print(0)
elif a[n - 1] > a[0]:
	if a != sorted(a):
		print(-1)
	else:
		print(0)
else:
	f = 0
	for i in range(0, n - 1):
		t = a[i + 1] - a[i]
		if t < 0:
			f += 1
		if f == 2:
			break
	if f == 2:
		print(-1)
	else:
		for i in range(n - 1, 0, -1):
			if a[i] == s[0] and a[i - 1] != s[0]:
				ind = i
				break
		print(n - ind)


from sys import stdin
n = int(stdin.readline())
a = list(map(int, stdin.readline().rstrip().split()))
a = a + a
y = 1
flag = 0
for i in range(2 * n - 1):
	if a[i + 1] >= a[i]:
		y += 1
		if y == n:
			flag = 1
			break
	else:
		y = 1
if flag == 1:
	if i + 2 - n == 0:
		print(0)
	else:
		print(n - (i + 2 - n))
else:
	print(-1)


n = int(input())
l = list(map(int, input().split()))
ind = n
for i in range(1, n):
	if l[i] >= l[i - 1]:
		continue
	else:
		ind = i
		break
lol = 0
if ind != n and l[n - 1] > l[0]:
	lol = 1
for i in range(ind, n - 1):
	if l[i] > l[i + 1]:
		lol = 1
		break
if lol:
	print(-1)
else:
	print(n - ind)


n = int(input())
L = list(map(int, input().split(' ')))
i = 0
if len(L) < 1:
	print(0)
else:
	while i + 1 < len(L) and L[i] <= L[i + 1]:
		i = i + 1
	j = i + 1
	k = 0
	while j < len(L) and L[j] <= L[0] and (L[j] <= L[(j + 1) % n]):
		j = j + 1
		k = k + 1
	if j != n:
		print(-1)
	else:
		print(k)


n = int(input())
a = list(map(int, input().split()))
d = []
for i in range(1, n):
	d.append(a[i] - a[i - 1])
d.append(a[0] - a[n - 1])
cnt = 0
for i in range(0, n):
	if d[i] < 0:
		cnt += 1
		pos = i
if cnt == 0:
	print(0)
elif cnt > 1:
	print(-1)
else:
	print(n - pos - 1)


import sys
input = sys.stdin.readline
n = int(input())
a = list(map(int, input().split()))
i = 1
aSorted = sorted(a)
while i < n and a[i] >= a[i - 1]:
	i += 1
a = a[i:] + a[:i]
for j in range(n):
	if aSorted[j] != a[j]:
		print(-1)
		break
else:
	print((n - i) % n)


n = int(input())
list1 = list(map(int, input().split()))
f = 0
s = 0
k = 0
for i in range(n - 1):
	if list1[i] <= list1[i + 1]:
		continue
	else:
		f += 1
		k = i + 1
if f == 1 and list1[n - 1] <= list1[0] or f == 0:
	if k == 0:
		print(k)
	else:
		print(n - k)
else:
	print(-1)


n = int(input())
a = [int(x) for x in input().split()]
count = 0
if a == sorted(a):
	print(0)
else:
	p = min(a)
	for i in range(n):
		if a[(i + 1) % n] - a[i] < 0:
			count += 1
		if count > 1:
			print(-1)
			break
	if count <= 1:
		if a[0] == a[n - 1] == p:
			j = n - 1
			fl = 0
			while p == a[j]:
				j -= 1
				fl += 1
			print(fl)
		else:
			print(n - a.index(p))


def mi():
	return map(int, input().split())

def li():
	return list(mi())

def ii():
	return int(input())
n = ii()
a = li()
f1 = 0
f2 = 0
c = 0
x = a[0]
for i in range(n - 1, -1, -1):
	if a[i] <= x:
		c += 1
		x = a[i]
	else:
		break
i += 1
a = a[i:] + a[:i]
for i in range(1, n):
	if a[i] > a[i - 1]:
		f2 = 1
	if a[i] < a[i - 1]:
		f1 = 1
		break
if f1:
	print('-1')
elif f2 == 0:
	print('0')
else:
	print(c)


num1 = 0
num2 = 0
n = int(input())
listMe = list(map(int, input().split()))
for i in range(n):
	if listMe[i] < num1:
		num2 = i
		break
	num1 = listMe[i]
newAs = listMe[num2:] + listMe[:num2]
if newAs == sorted(listMe):
	print((n - num2) % n)
else:
	print(-1)


n = int(input())
arr = list(map(int, input().split()))
cnt = 0
index = -1
for i in range(1, n):
	if arr[i - 1] > arr[i]:
		cnt += 1
		index = i
if cnt == 0:
	print('0')
elif cnt == 1 and arr[n - 1] <= arr[0]:
	print(n - index)
else:
	print('-1')


n = int(input())
A = [int(i) for i in input().split()]
B = A[:]
B.sort()
Neg = 0
c = True
D = []
index = -1
if B == A:
	print(0)
else:
	for i in range(1, n):
		if i == n - 1:
			d = A[i] - A[i - 1]
			if d < 0:
				Neg += 1
				index = i
			if A[0] - A[i] < 0:
				Neg += 1
		else:
			d = A[i] - A[i - 1]
			if d < 0:
				Neg += 1
				index = i
			if d >= 0:
				D.append(d)
	if c == True and Neg <= 1:
		print(n - index)
	else:
		print(-1)


import copy
M = 998244353
n = int(input())
a = [int(i) for i in input().split()]
f = [0] * (2 * n + 1)
p = [0] * (2 * n + 1)
p[0] = 1
b = sorted(copy.copy(a))
qaq = [0] * (n + 1)
a = a + a
for i in range(1, 2 * n + 1):
	p[i] = p[i - 1] * 131 % M
	f[i] = (f[i - 1] * 131 + a[i - 1]) % M
for i in range(1, n + 1):
	qaq[i] = (qaq[i - 1] * 131 + b[i - 1]) % M
ans = -1
for i in range(n + 1):
	v1 = (f[i + n] - f[i] * p[n] + M) % M
	v2 = (qaq[n] - qaq[0] * p[n] + M) % M
	if v1 == v2:
		ans = n - i
if ans < 0:
	print(ans)
else:
	print(ans % n)


import os
import sys
from io import BytesIO, IOBase
import bisect
import math

def main():
	n = int(input())
	a = list(map(int, input().split()))
	flag = 0
	for i in range(n - 1):
		if a[i] > a[i + 1]:
			flag = 1
			break
	if not flag:
		print(0)
	else:
		new = a[i + 1:] + a[:i + 1]
		if new == sorted(a):
			print(n - i - 1)
		else:
			print(-1)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


n = int(input())
v = list(map(int, input().split()))
(cnt, ans) = (0, 0)
for i in range(1, n):
	if v[i] < v[i - 1]:
		cnt += 1
		ans = n - i
if cnt == 1 and v[0] >= v[-1] or cnt == 0:
	print(ans)
else:
	print(-1)


n = int(input())
a = [int(x) for x in input().split()]
flag = True
for i in range(1, n):
	if a[i] < a[i - 1]:
		flag = False
		break
if flag:
	print('0')
else:
	a = a[i:] + a[:i]
	for j in range(1, n):
		if a[j] < a[j - 1]:
			print('-1')
			break
	else:
		print(n - i)


n = int(input())
vet = input().split()
vet[0] = int(vet[0])
menor = vet[0]
ind_menor = 0
possible = True
for i in range(1, n):
	vet[i] = int(vet[i])
	if vet[i] < menor or (vet[i] == menor and vet[i - 1] != vet[i]):
		menor = vet[i]
		ind_menor = i
ordened_vet = vet[ind_menor:] + vet[:ind_menor]
for i in range(1, n):
	if ordened_vet[i] < ordened_vet[i - 1]:
		possible = False
		break
if possible and ind_menor == 0:
	print('0')
elif possible and menor == ordened_vet[0] and (ordened_vet[0] == ordened_vet[-1]):
	print('0')
elif possible:
	print(n - ind_menor)
else:
	print('-1')


def s(a, i):
	s = i
	while i + 1 < len(a):
		if a[i] <= a[i + 1]:
			i += 1
		else:
			return a[s:i + 1]
	return a[s:i + 1]
n = int(input())
a = list(map(int, input().split()))
b = s(a, 0)
c = s(a, len(b))
if len(b) == n:
	print(0)
elif len(b) + len(c) == n and c[len(c) - 1] <= b[0]:
	print(len(c))
else:
	print(-1)


n = int(input())
a = [int(x) for x in input().split()]
violate = pos = 0
for i in range(1, n):
	if a[i] < a[i - 1] and violate == 0:
		violate = 1
		pos = i
	elif a[i] < a[i - 1]:
		violate = 2
		break
if violate == 0:
	print(0)
elif violate == 1 and a[n - 1] <= a[0]:
	print(n - pos)
else:
	print(-1)


import sys
n = int(input())
v = [int(i) for i in input().split()]
last = -1
first = v[0]
for i in range(len(v)):
	if v[i] < last:
		break
	else:
		last = v[i]
else:
	print(0)
	sys.exit()
pos = i
last = -1
for i in range(i, len(v)):
	if v[i] < last or v[i] > first:
		print(-1)
		sys.exit()
	else:
		last = v[i]
print(len(v) - pos)


n = int(input())
x = list(map(int, input().split()))
b = []
for i in x:
	b.append(i)
b.reverse()
if x == sorted(x):
	print(0)
	exit()
elif sorted(x) == b and n != 2:
	print(-1)
	exit()
elif x[-1] > x[0]:
	print(-1)
	exit()
elif x[-1] < x[0] or x[-1] == x[0]:
	r = 0
	j = -1
	k = 0
	while x[j] < x[k] or x[j] == x[k]:
		r += 1
		j -= 1
		k -= 1
	if x[:j + 1] == sorted(x[:j + 1]):
		print(r)
		exit()
	else:
		print(-1)
		exit()


n = int(input())
a = list(map(int, input().split()))
b = -1
for i in range(1, n):
	if a[i - 1] > a[i]:
		b = i
		break
if b == -1:
	print(0)
else:
	c = a[b:] + a[:b]
	flag = 0
	for i in range(1, n):
		if c[i] < c[i - 1]:
			flag = 1
			break
	if flag == 1:
		print(-1)
	else:
		print(n - b)


def one_shift(n, x):
	c = x.copy()
	c.sort()
	if c == x:
		return 0
	set = 0
	for i in range(n):
		if x[i + 1] < x[i] and (not set):
			set = 1
			if x[i + 1:] + x[:i + 1] == c:
				return n - i - 1
			else:
				return -1
		if x[i + 1] < x[i] and set:
			return -1
	return n - i - 1
n = int(input())
x = list(map(int, input().split()))
print(one_shift(n, x))


import sys

def minindex(alist):
	index = -1
	min = 1000000
	for (idx, num) in enumerate(alist):
		if num < min:
			index = idx
			min = num
	return index

def isSorted(array):
	min = 0
	for num in array:
		if num < min:
			return False
		min = num
	return True
nums = int(sys.stdin.readline())
numbers = [int(num) for num in sys.stdin.readline().split()[0:nums]]
index = minindex(numbers)
min = numbers[index]
moves = 0
if index == 0:
	for num in range(nums - 1, -1, -1):
		if num == 0:
			moves = 0
			break
		if numbers[num] == min:
			moves = moves + 1
		else:
			break
	newnumbers = numbers[index:nums - moves]
	if isSorted(newnumbers):
		print(moves)
	else:
		print(-1)
else:
	newnumbers = numbers[index:]
	newnumbers.extend(numbers[0:index])
	if isSorted(newnumbers):
		print(nums - index)
	else:
		print(-1)


n = int(input())
a = list(map(int, input().split()))
if a == sorted(a):
	print(0)
else:
	m = a.index(max(a))
	while m < n - 1:
		if a[m] == a[m + 1]:
			m += 1
		else:
			break
	l = a[:m + 1]
	r = a[m + 1:]
	if r == sorted(r) and l == sorted(l) and (max(r) <= l[0]):
		print(n - m - 1)
	else:
		print(-1)


n = int(input())
x = list(map(int, input().split()))
(flag, cnt, prev_max, prev_min) = (0, 0, 0, x[0])
if n == 2:
	if x[0] <= x[1]:
		print(0)
	else:
		print(1)
else:
	for i in range(1, n):
		if flag == 0:
			if x[i] < x[i - 1]:
				flag = 1
				cnt += 1
				prev_max = x[i - 1]
				if x[i] > prev_min:
					cnt = -1
					break
		elif flag == 1:
			if prev_max >= x[i] >= x[i - 1]:
				cnt += 1
			if x[i] < x[i - 1] or x[i] > prev_max or x[i] > prev_min:
				cnt = -1
				break
	print(cnt)


n = int(input())
a = [*map(int, input().split())]
for i in range(n - 1):
	if a[i] > a[i + 1]:
		print(n - i - 1 if sorted(a) == a[i + 1:] + a[:i + 1] else -1)
		quit()
print(0)


def zip_sorted(a, b):
	(a, b) = zip(*sorted(zip(a, b)))
	sorted(zip(a, b), key=lambda x: x[1])
	return (a, b)
n = int(input())
a = [int(n1) for n1 in input().split()]
count2 = 0
for k1 in range(len(a) - 1):
	if a[k1] <= a[k1 + 1]:
		pass
	else:
		count2 = count2 + 1
		index1 = k1
if count2 == 0:
	print(0)
if count2 == 1:
	if sorted(a[:index1 + 1]) == a[:index1 + 1]:
		if sorted(a[index1 + 1:]) == a[index1 + 1:]:
			if a[0] >= a[index1 + 1] and a[0] >= a[-1] and (a[index1] >= a[index1 + 1]) and (a[index1] >= a[index1 + 1]):
				print(len(a[index1 + 1:]))
			else:
				print(-1)
		else:
			print(-1)
	else:
		print(-1)
if count2 > 1:
	print(-1)


n = int(input())
l = list(map(int, input().split()))
v = 0
for i in range(n - 1):
	if l[i] > l[i + 1]:
		s = i
		v += 1
if l[n - 1] > l[0]:
	s = n - 1
	v += 1
if v == 0:
	print(0)
elif v > 1:
	print(-1)
else:
	print(n - 1 - s)


from sys import stdin, stdout
from os import path
rd = lambda : stdin.readline().strip()
wr = stdout.write
if path.exists('input.txt'):
	stdin = open('input.txt', 'r')
import time, math
x = int(rd())
mylist = list(map(int, rd().split()))
left = mid = right = 0
while mid + 1 < x and mylist[mid + 1] >= mylist[mid]:
	mid += 1
right = mid
if right + 1 < x:
	right = mid + 1
while right + 1 < x and mylist[right + 1] >= mylist[right]:
	right += 1
if right < x - 1 or (mylist[-1] > mylist[0] and mid != x - 1):
	print(-1)
else:
	print(right - mid)


n = int(input())
alist = [int(x) for x in input().split()]
fault = 0
for i in range(n):
	if alist[i - 1] <= alist[i]:
		pass
	else:
		fault += 1
		if fault > 1:
			print(-1)
			quit()
		f = i
if fault == 0:
	print(0)
	quit()
print((n - f) % n)


def KMPSearch(pat, txt):
	M = len(pat)
	N = len(txt)
	val = -1
	lps = [0] * M
	j = 0
	computeLPSArray(pat, M, lps)
	i = 0
	while i < N:
		if pat[j] == txt[i]:
			i += 1
			j += 1
		if j == M:
			val = i - j
			j = lps[j - 1]
			break
		elif i < N and pat[j] != txt[i]:
			if j != 0:
				j = lps[j - 1]
			else:
				i += 1
	return val

def computeLPSArray(pat, M, lps):
	len = 0
	lps[0]
	i = 1
	while i < M:
		if pat[i] == pat[len]:
			len += 1
			lps[i] = len
			i += 1
		elif len != 0:
			len = lps[len - 1]
		else:
			lps[i] = 0
			i += 1
var = -1
n = int(input())
arr = [int(i) for i in input().split()]
temp = [i for i in arr]
temp.sort()
arr += arr
txt = arr
pat = temp
t1 = KMPSearch(pat, txt)
if t1 >= 0:
	print((n - t1) % n)
else:
	print(-1)


import os
import sys
from io import BytesIO, IOBase

def solution(arr, n):
	idx = -1
	for i in range(n - 1):
		if arr[i] > arr[i + 1]:
			idx = i
			break
	if idx == -1:
		write(0)
		return
	if arr[idx + 1:] + arr[:idx + 1] == sorted(arr):
		write(n - 1 - idx)
	else:
		write(-1)

def main():
	n = r_int()
	arr = r_array()
	solution(arr, n)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))

def input():
	return sys.stdin.readline().rstrip('\r\n')

def write(*args, end='\n'):
	for x in args:
		sys.stdout.write(str(x) + ' ')
	sys.stdout.write(end)

def r_array():
	return [int(x) for x in input().split()]

def r_int():
	return int(input())
main()


a = int(input())
s = [int(i) for i in input().split()]
i = 0
c = 0
if sorted(s) == s:
	print(0)
elif s[-1] > s[0]:
	print(-1)
else:
	while s[i + 1] >= s[i]:
		i += 1
	for j in range(i + 1, len(s) - 1):
		if s[j + 1] < s[j]:
			break
		else:
			c += 1
	if c == len(s) - i - 2:
		print(len(s) - i - 1)
	else:
		print(-1)


import sys
import array
import heapq

def solve(arr, n):
	idx = 0
	m = 0
	while idx < n - 1:
		if arr[idx] <= arr[idx + 1]:
			m += 1
		else:
			break
		idx += 1
	can = 1
	for i in range(m + 1, n):
		if arr[i] > arr[0]:
			can = 0
			break
	for i in range(m + 1, n - 1):
		if arr[i] > arr[i + 1]:
			can = 0
			break
	if can:
		return n - m - 1
	else:
		return -1
n = int(input())
arr = list(input().split(' '))
for i in range(len(arr)):
	arr[i] = int(arr[i])
print(solve(arr, n))


n = int(input())
lst = list(map(int, input().split(' ')))
diffs = []
for t in range(len(lst) - 1):
	diffs.append(lst[t + 1] - lst[t])
diffs.append(lst[0] - lst[-1])
lista = [x for x in diffs if x < 0]
if len(lista) != 1:
	if max(diffs) == 0:
		print(0)
	else:
		print(-1)
else:
	diffs.reverse()
	index = diffs.index(lista[0])
	if index == 0:
		print(0)
	else:
		print(index)


import sys
from math import *

def solve():
	n = int(input())
	a = list(map(int, input().split()))
	ok = 0
	t = 0
	if a == sorted(a):
		print(0)
		return 0
	if len(a) == 2:
		print(1)
		return 0
	for i in range(n - 1):
		if a[i] <= a[i + 1]:
			ok += 1
		else:
			t = i + 1
			break
	b = a[t:n]
	if b == sorted(b):
		if b[-1] > a[0]:
			print(-1)
		else:
			print(n - t)
	else:
		print(-1)
solve()


n = int(input())
a = [int(i) for i in input().split()]
b = sorted(a)
if b == a:
	print(0)
else:
	index = -1
	for i in range(1, n):
		if a[i] < a[i - 1]:
			index = i
			break
	c = a[i:] + a[:i]
	if c == b:
		print(n - i)
	else:
		print(-1)


n = int(input())
a = list(map(int, input().split()))
p_i = 0
for i in range(n - 1):
	if a[i] > a[i + 1]:
		p_i = i + 1
b = a[p_i:] + a[:p_i]
result = 1
for i in range(n - 1):
	if b[i] > b[i + 1]:
		result = 0
if result == 0:
	print(-1)
else:
	print((n - p_i) % n)


n = int(input())
a = list(map(int, input().split()))
f = True
for i in range(n - 1, 0, -1):
	if a[i] < a[i - 1]:
		f = False
		break
if f:
	print(0)
else:
	a = a[i:] + a[:i]

	def ifsorted(a, n, i):
		for j in range(1, n):
			if a[j] < a[j - 1]:
				return -1
		return n - i
	print(ifsorted(a, n, i))


a = int(input())
b = list(map(int, input().split()))
sort = 2
for i in range(1, a):
	if b[i] < b[i - 1]:
		sort -= 1
if b[-1] > b[0]:
	sort -= 1
if sort > 0:
	x = min(b)
	b = b[::-1]
	while b[-1] == x and len(b) > 1:
		b.pop(-1)
	b = b[::-1]
	x = min(b)
	y = b.index(x)
	if b == sorted(b):
		print(0)
	else:
		print(len(b) - y)
else:
	print(-1)


n = int(input())
arr = list(map(int, input().split()))
go = False
go2 = False
if arr[-1] <= arr[0]:
	reset = 1
	prev = arr[0]
	sr_idx = None
	for i in range(1, n):
		if arr[i] < prev:
			if reset < 2:
				reset += 1
				sr_idx = i
			else:
				print(-1)
				go2 = True
				break
		prev = arr[i]
else:
	go = True
	if n == 2:
		print(0)
	else:
		print(-1)
if not go and (not go2):
	if sr_idx == None:
		print(0)
	elif reset == 2:
		print(n - sr_idx)


n = int(input())
ar = list(map(int, input().split()))
i = 0
minIndex = 0
ntTrue = True
while i < n - 1:
	if ar[i] > ar[i + 1] and minIndex != 0:
		ntTrue = False
		break
	elif ar[i] > ar[i + 1] and minIndex == 0:
		minIndex = i + 1
	i += 1
if ntTrue == False:
	print(-1)
elif minIndex == 0:
	print(0)
elif ar[0] < ar[-1]:
	print(-1)
else:
	print(n - minIndex)


def issorted(d):
	for i in range(1, len(d)):
		if d[i - 1] > d[i]:
			return False
	return True
n = int(input())
d = list(map(int, input().split()))
if issorted(d):
	print(0)
for i in range(1, n):
	if d[i - 1] > d[i]:
		p = d[i:] + d[:i]
		if issorted(p):
			print(n - i)
			break
		else:
			print(-1)
			break


n = int(input())
list = list(map(int, input().split()))
list2 = []
c = 0
for i in range(0, n - 1):
	if list[i] > list[i + 1]:
		c = c + 1
		list2.append(i)
if n > 3:
	if c == 1:
		if list[n - 1] <= list[0]:
			print(n - 1 - list2[0])
		else:
			print('-1')
	elif c == 0:
		print('0')
	else:
		print('-1')
elif c == 1:
	if list[n - 1] <= list[0]:
		print(n - 1 - list2[0])
	else:
		print('-1')
elif c == 0:
	print('0')
else:
	print('-1')


l = int(input())
s = input().split(' ')
seq = []
for i in s:
	seq.append(int(i))
changes = 0
index = 0
for i in range(1, l):
	curr = seq[i]
	prev = seq[i - 1]
	if curr >= prev:
		continue
	elif changes <= 1:
		index = i
		changes += 1
	else:
		break
if seq[0] < seq[l - 1]:
	changes += 1
if changes <= 1:
	if index == 0:
		print(0)
	else:
		print(l - index)
else:
	print(-1)


n = int(input())
l = list(map(int, input().split()))
flag = False
flag2 = False
index = n - 1
for i in range(n - 1):
	if l[i + 1] < l[i]:
		if flag:
			flag2 = True
			break
		else:
			flag = True
			index = i
if flag2 or (flag and l[-1] > l[0]):
	print(-1)
else:
	print(n - index - 1)


from sys import stdin, stderr

def readInts():
	return map(int, stdin.readline().strip().split())

def print_err(*args, **kwargs):
	print(*args, file=stderr, **kwargs)

def solve(n, ns):
	v = ns[0]
	v0 = v
	inversions = 0
	iix = n
	for ix in range(1, n):
		v2 = ns[ix]
		if v2 < v:
			inversions += 1
			iix = ix
		if inversions > 1:
			return -1
		if inversions and v2 > v0:
			return -1
		v = v2
	return n - iix

def run():
	(n,) = readInts()
	ns = list(readInts())
	print(solve(n, ns))
run()


n = int(input())
a = list(map(int, input().split()))
a = a + a
cn = 1
for i in range(2 * n - 2, 0, -1):
	if a[i] <= a[i + 1]:
		cn += 1
	else:
		cn = 1
	if cn == n:
		print(n - i)
		exit()
print(-1)
exit()
n = int(input())
print('\n'.join(('*' * abs(i) + 'D' * (n - 2 * abs(i)) + '*' * abs(i) for i in range(-(n // 2), n // 2 + 1))))
exit()
s = input()
if len(s) > 2:
	s = s[-2:]
n = int(s)
print((1 + 2 ** n + 3 ** n + 4 ** n) % 5)
exit()
n = int(input())
for i in range(n):
	(x, y) = map(int, input().split())
	if x != y:
		print('Happy Alex')
		exit()
print('Poor Alex')


n = int(input())
s = list(map(int, input().split()))
t = []
a = 0
if s == sorted(s):
	print(0)
	exit()
for i in range(n):
	if s[i] > s[i + 1]:
		t = s[i + 1:]
		s = s[:i + 1]
		a = i
		break
t.extend(s)
if t == sorted(t) and s == sorted(s):
	print(n - a - 1)
else:
	print(-1)


n = int(input())
ll = list(map(int, input().split()))
k = ll[0]
t = True
ans = 0
for i in range(1, n):
	if ll[i] < k:
		k = ll[i]
		ans += 1
		for j in range(i + 1, n):
			if ll[j] < k:
				t = False
				break
			ans += 1
			k = ll[j]
		break
	else:
		k = ll[i]
if t == True:
	if ll[0] >= ll[-1] and ans > 0:
		print(ans)
	elif ans == 0:
		print(0)
	else:
		print(-1)
else:
	print(-1)


n = int(input())
l = list(map(int, input().split()))
c = 0
for i in range(1, n):
	if l[i] < l[i - 1]:
		l = l[i:] + l[:i]
		c = 1
		z = i
		break
if l == sorted(l):
	if c == 0:
		print(0)
	else:
		print(n - z)
else:
	print(-1)


mod = 1000000007
ii = lambda : int(input())
si = lambda : input()
dgl = lambda : list(map(int, input()))
f = lambda : map(int, input().split())
il = lambda : list(map(int, input().split()))
ls = lambda : list(input())
n = ii()
l = il()
l1 = sorted(l[:])
for i in range(n - 1):
	if l[i] > l[i + 1]:
		if l[i + 1:] + l[:i + 1] == l1:
			exit(print(n - i - 1))
		else:
			exit(print(-1))
print(0)


n = int(input())
a = list(map(int, input().split(' ')))
if a == sorted(a) or len(a) == 1:
	print(0)
else:
	chk = 1
	x = 0
	ans = 0
	t = 0
	while x < n - 1 and a[x] <= a[x + 1]:
		x = x + 1
	t = x + 1
	if sorted(a[t:]) == a[t:] and a[n - 1] <= a[0]:
		print(n - t)
	else:
		print(-1)


n = int(input())
lst = [int(x) for x in input().split()]
index = 0
count = 0
for i in range(n):
	if lst[i - 1] > lst[i]:
		index = i
		count += 1
	if count == 2:
		print(-1)
		break
if count != 2:
	print((n - index) % n)


(n, A) = (int(input()), list(map(int, input().split())))
(flag, shifts) = (False, 0)
for i in range(n):
	if A[i] > A[i - n + 1]:
		if flag:
			print(-1)
			break
		(flag, shifts) = (True, n - i - 1)
else:
	print(shifts)


def R():
	return map(int, input().split())

def I():
	return int(input())

def S():
	return str(input())

def L():
	return list(R())
from collections import Counter
import math
import sys
from itertools import permutations
import bisect
mod = 10 ** 9 + 7
n = I()
a = L()
for i in range(n - 1):
	if a[i] > a[i + 1]:
		break
if i == n - 2 and a[n - 2] <= a[n - 1]:
	print('0')
	exit()
for j in range(i + 1, n - 1):
	if a[j] > a[j + 1]:
		print('-1')
		exit()
print([n - 1 - i, '-1'][a[0] < a[n - 1]])


n = int(input())
l = list(map(int, input().split()))
a = []
b = []
j = n
for i in range(1, n + 1):
	a.append(l[i - 1])
	if i < n:
		if l[i] < l[i - 1]:
			j = i
			b = l[i:]
			break
if b + a == sorted(l):
	print(n - j)
else:
	print(-1)


(n, s, r) = (int(input()), input(), -1)
k = (s + ' ' + s).replace('  ', ' ')
q = ' '.join(map(str, sorted(map(int, s.split()))))
if q in k:
	r = len(list(map(int, s[:k.index(q)].split())))
print(n - r if q in k and r != 0 else 0 if r == 0 else -1)


from sys import exit
n = int(input())
inp = input().split()
nums = [int(x) for x in inp]
if nums[-1] > nums[0]:
	if nums == sorted(nums):
		print(0)
	else:
		print(-1)
	exit()
c = 0
t = 1
for i in range(1, n):
	if nums[i - 1] > nums[i]:
		t -= 1
	if t == 0:
		c += 1
	elif t == -1:
		print(-1)
		exit()
print(c)


n = int(input())
nums = list(map(int, input().split(' ')))
dif_count = 0
dif_indx = -1
for i in range(1, n):
	if nums[i] < nums[i - 1]:
		dif_indx = i
		dif_count += 1
if nums[n - 1] > nums[0]:
	dif_count += 1
if dif_indx == -1:
	print(0)
elif dif_count > 1:
	print(-1)
else:
	print(n - dif_indx)


n = int(input())
l = list(map(int, input().split()))
d = 0
c = 0
for i in range(1, n):
	if d == 2:
		break
	elif l[i] >= l[i - 1] and c == 0:
		j = i
		c = 1
	elif l[i] >= l[i - 1] and c != 0:
		continue
	elif l[i] < l[i - 1]:
		d += 1
		k = i
if d == 2:
	print(-1)
elif d == 0:
	print(0)
elif d == 1:
	if l[-1] > l[0]:
		print(-1)
	else:
		print(n - k)


n = int(input())
a = []
ID = input().split()
for i in range(n):
	a.append(int(ID[i]))
k = 0
while k < n - 1 and a[k] <= a[k + 1]:
	k += 1
i = k + 1
flag = False
while i < n - 1:
	if a[i] > a[i + 1]:
		flag = True
	i += 1
if k < n - 1 and a[n - 1] > a[0]:
	flag = True
if flag == True:
	print(-1)
else:
	print(n - 1 - k)


n = int(input())
s = list(map(int, input().split()))
k = sorted(s)
m = min(s)
if m == s[0]:
	c = 0
	s.reverse()
	for j in s:
		if j == m:
			c += 1
		else:
			break
	v = n - c
	s.reverse()
else:
	v = s.index(m)
x = s[v:n]
e = []
for i in range(n - len(x)):
	e.append(s[i])
if s == k:
	print(0)
elif x + e == k:
	print(len(x))
else:
	print(-1)


n = int(input())
l = list(map(int, input().split()))
ind = n
for i in range(n - 1):
	if l[i] > l[i + 1]:
		ind = i + 1
		break
flag = True
for i in range(n - 1):
	if l[(i + ind) % n] > l[(i + ind + 1) % n]:
		flag = False
		break
if flag == True:
	print(n - ind)
else:
	print(-1)


n = int(input())
arr = list(map(int, input().split()))
(idx, mn) = (1, arr[0])
while idx < n:
	while idx < n and arr[idx] >= arr[idx - 1]:
		idx += 1
		mn = min(mn, arr[0])
	if idx == n:
		print(0)
		break
	ref = idx
	idx += 1
	while idx < n and arr[idx] >= arr[idx - 1]:
		idx += 1
	if idx < n or arr[idx - 1] > mn:
		print(-1)
	else:
		print(n - ref)
	break


n = int(input())
a = list(map(int, input().split()))
ii = -1
c = 0
for i in range(1, len(a)):
	if a[i] < a[i - 1]:
		ii = i
		c += 1
if ii is -1:
	print(0)
elif c is 1 and a[len(a) - 1] <= a[0]:
	print(len(a) - ii)
else:
	print(-1)


n = int(input())
mp = map(int, input().split())
a = []
for i in mp:
	a.append(i)
invp = 0
inve = 0
res = True
for i in range(1, n):
	if a[i] < a[i - 1]:
		if invp == 0:
			invp = i
		else:
			res = False
			break
if a[0] < a[n - 1] and invp != 0:
	res = False
ans = (n - invp) % n
if res:
	print(ans)
else:
	print(-1)


n = int(input())
L = list(map(int, input().split()))
i = n - 1
while L[i - 1] <= L[i]:
	i -= 1
	if i == 0:
		break
if L[i:] + L[:i] == sorted(L):
	print((n - i) % n)
else:
	print('-1')


n = int(input())
li = list(map(int, input().split()))[:n]
li2 = sorted(li)
count = 0
pos = 0
for i in range(n):
	if li[i - 1] > li[i]:
		count += 1
		pos = i
if li == li2:
	print(0)
elif count > 1:
	print(-1)
else:
	print(n - pos)


n = int(input())
a = list(map(int, input().split()))
ans = 0
d = 0
for x in range(1, n):
	if a[x - 1] > a[x]:
		d = 1
		if sorted(a) == a[x:] + a[:x]:
			ans = n - x
		else:
			ans = -1
		break
if d == 0:
	print(0)
else:
	print(ans)


n = int(input())
a = [int(x) for x in input().split()]
prev = 0
li = 0
if a == sorted(a):
	print(0)
	exit()
for i in range(n):
	if a[i] < prev:
		li = i
		break
	prev = a[i]
if sorted(a) == a[li:] + a[:li]:
	print(n - li)
else:
	print(-1)


check = True
n = int(input())
nums = [int(x) for x in input().split()]
current = 0
res = 0
for i in range(n):
	if nums[i] < current:
		if check:
			check = False
			res = 1
		else:
			print(-1)
			exit()
	elif not check:
		res += 1
	current = nums[i]
if check:
	print(0)
elif nums[n - 1] <= nums[0]:
	print(res)
else:
	print(-1)


import math, string, itertools, fractions, heapq, collections, re, array, bisect, sys, random, time, copy, functools
sys.setrecursionlimit(10 ** 7)
inf = 10 ** 20
eps = 1.0 / 10 ** 10
mod = 10 ** 9 + 7
dd = [(-1, 0), (0, 1), (1, 0), (0, -1)]
ddn = [(-1, 0), (-1, 1), (0, 1), (1, 1), (1, 0), (1, -1), (0, -1), (-1, -1)]

def LI():
	return [int(x) for x in sys.stdin.readline().split()]

def LI_():
	return [int(x) - 1 for x in sys.stdin.readline().split()]

def LF():
	return [float(x) for x in sys.stdin.readline().split()]

def LS():
	return sys.stdin.readline().split()

def I():
	return int(sys.stdin.readline())

def F():
	return float(sys.stdin.readline())

def S():
	return input()

def pf(s):
	return print(s, flush=True)

def main():
	n = I()
	a = LI()
	aa = a + a
	t = []
	for i in range(n * 2 - 1):
		if aa[i] > aa[i + 1]:
			t.append(i)
	if len(t) < 2:
		return 0
	if len(t) > 2:
		return -1
	return n - t[0] - 1
print(main())


n = int(input())
s = list(map(int, input().split()))[:n]
t = s
s0 = sorted(s)
c = 0
for i in range(n):
	if t[i - 1] > t[i]:
		c += 1
if t == s0:
	print(0)
elif c > 1 or t[n - 1] > t[0]:
	print(-1)
else:
	for i in range(n):
		if t[i] > t[i + 1]:
			print(n - i - 1)
			break


n = int(input())
l = list(map(int, input().split()))
d = 0
for i in range(1, n):
	if l[i] < l[i - 1]:
		d = i
		break
san = l[i:] + l[:i]
if d != 0:
	l.sort()
	if l == san:
		print(n - d)
	else:
		print(-1)
else:
	print(0)


n = int(input())
ll = list(map(int, input().split()))

def afz(l):
	return all((l[i] >= l[i - 1] for i in range(1, len(l))))
k = -1
for i in range(1, n):
	if ll[i] < ll[i - 1]:
		k = i
if k == -1:
	print(0)
elif (afz(ll[:k]) and afz(ll[k:])) and ll[-1] <= ll[0]:
	print(n - k)
else:
	print(-1)


n = int(input())
lst = list(map(int, input().strip().split(' ')))
f = 0
for j in range(1, n):
	if lst[j] >= lst[j - 1]:
		if j == n - 1:
			f = 1
		continue
	else:
		break
if f == 1:
	print(0)
else:
	k = []
	p = []
	for i in range(j, n):
		k.append(lst[i])
		p.append(lst[i])
	for i in range(j):
		k.append(lst[i])
		p.append(lst[i])
	p.sort()
	if k == p:
		print(n - j)
	else:
		print('-1')


n = int(input())
lst = list(map(int, input().split()))
count = 0
for i in range(n - 1):
	if lst[i] > lst[i + 1]:
		count += 1
		index = i
		break
if count != 0:
	lst2 = lst[index + 1:n]
	count = len(lst2)
	for i in range(index + 1):
		lst2.append(lst[i])
	if lst2 != sorted(lst):
		count = -1
print(count)


from collections import *
from bisect import *
from math import *
from heapq import *
from fractions import *
import sys
input = sys.stdin.readline
t = 1

def r(a):
	return a * (a - 1) // 2
while t:
	t -= 1
	n = int(input())
	a = list(map(int, input().split()))
	b = a[:]
	b.sort()
	s = 0
	pos = -1
	for i in range(n - 1):
		if a[i] > a[i + 1]:
			pos = i
			break
	a = a[pos + 1:] + a[:pos + 1]
	if pos == -1:
		print(0)
		exit(0)
	if b == a:
		print(n - pos - 1)
	else:
		print(-1)


n = int(input())
a = list(map(int, input().split()))
a.append(max(a) + 1)
x = -1
for i in range(n):
	if a[i] > a[i + 1]:
		x = i + 1
		break
count = 0
y = 0
if x != -1:
	y = x
for i in range(y, n):
	if a[i] <= a[i + 1]:
		count += 1
if x == -1:
	print(0)
elif count == len(a[x:]) - 1 and a[n - 1] <= a[0]:
	print(count)
else:
	print(-1)


from sys import stdin
stdin.readline

def mp():
	return list(map(int, stdin.readline().strip().split()))

def it():
	return int(stdin.readline().strip())
from collections import defaultdict as df
n = it()
l = mp()
i = 0
while i < n - 1:
	if l[i] <= l[i + 1]:
		i += 1
	else:
		break
a = l[i + 1:] + l[:i + 1]
l.sort()
if l == a:
	print(n - i - 1)
else:
	print(-1)


n = int(input())
a = list(map(int, input().split()))
if a == sorted(a):
	print('0')
elif a == sorted(a, reverse=True):
	if n == 2:
		print(n - 1)
	else:
		print('-1')
else:
	limit = a[0]
	if a[1] < a[0]:
		if a[1:] == sorted(a[1:]) and a[len(a) - 1] <= limit:
			print(len(a[1:]))
		else:
			print('-1')
	else:
		ct = 0
		pos = -1
		for x in range(1, len(a) - 1):
			if a[x] >= a[x - 1] and a[x] > a[x + 1]:
				ct += 1
				pos = x
		if ct == 1 and a[pos + 1:] == sorted(a[pos + 1:]) and (a[len(a) - 1] <= limit):
			print(len(a[pos + 1:]))
		else:
			print('-1')


n = int(input())
inp = input().split(' ')
inp = list(map(int, inp))
num = 0
pos = -1
for i in range(0, len(inp) - 1):
	if inp[i] > inp[i + 1] and num == 0:
		num = num + 1
		pos = i
	elif inp[i] > inp[i + 1]:
		num = num + 1
if num == 0:
	print('0')
elif num > 1:
	print('-1')
elif num == 1:
	if inp[len(inp) - 1] <= inp[0]:
		print(len(inp) - pos - 1)
	else:
		print('-1')


n = int(input())
l = [*map(int, input().split())]
ii = 1
while ii < n and l[ii] >= l[ii - 1]:
	ii += 1
if all((l[(i + ii) % n] >= l[(ii + i - 1) % n] for i in range(1, n))):
	print(n - ii)
else:
	print(-1)


n = int(input())
inp = list(map(int, input().split()))
flag = -1
sorted_inp = sorted(inp)
for i in range(n - 1):
	if inp[i] > inp[i + 1]:
		flag = i
		break
if flag == -1:
	print(0)
	exit()
for i in range(flag + 1, n):
	if inp[i] != sorted_inp[i - flag - 1]:
		print(-1)
		exit()
print(n - flag - 1)


n = int(input())
l = list(map(int, input().split()))
l1 = []
m = l[n - 1]
c = 1
k = 0
if l == sorted(l):
	print(0)
else:
	for i in reversed(range(n - 1)):
		if l[i] <= m:
			c += 1
			m = l[i]
		else:
			k = i + 1
			break
	for i in range(k, n):
		l1.append(l[i])
	for i in range(0, k):
		l1.append(l[i])
	if l1 == sorted(l):
		print(c)
	else:
		print(-1)


n = int(input())
a = list(map(int, input().split()))
c1 = 0
c2 = 0
x = []
for i in range(1, n):
	if a[i] >= a[i - 1]:
		c1 += 1
	else:
		x.append(i)
		c2 += 1
if a[n - 1] > a[0] and c2 != 0:
	c2 = 2
if len(x) == 0:
	x = [n]
if c2 <= 1:
	print(n - x[0])
else:
	print(-1)


while True:
	try:

		def solution(n, a):
			incr = True
			cunt = 0
			for i in range(1, n, 1):
				if a[i] < a[i - 1]:
					incr = False
					cunt += 1
			if incr:
				print(0)
			else:
				prev = 10 ** 6
				(i, lan) = (n - 1, 0)
				while a[i] <= prev:
					lan += 1
					prev = a[i]
					i -= 1
				if cunt >= 2 or a[-1] > a[0]:
					print(-1)
				else:
					print(lan)

		def read():
			n = int(input())
			a = list(map(int, input().split()))
			solution(n, a)
		if __name__ == '__main__':
			read()
	except EOFError:
		break


n = int(input())
array = input()
array = list(map(int, array.split(' ')))
discordancias = 0
pos = 0
for i in range(1, n):
	if array[i] < array[i - 1]:
		discordancias += 1
		pos = i
	if discordancias > 1:
		break
if array[n - 1] > array[0] and discordancias > 0 or discordancias > 1:
	print(-1)
elif discordancias == 1:
	print(n - pos)
else:
	print(0)


n = int(input())
a = list(map(int, input().split()))
i = 1
b = [a[0]]
while i < len(a):
	if a[i - 1] <= a[i]:
		b += [a[i]]
	else:
		break
	i += 1
a = a[i:]
if a == sorted(a) and (len(a) == 0 or a[-1] <= b[0]):
	print(len(a))
else:
	print(-1)


def checkSort(a):
	for i in range(len(a) - 1):
		if a[i] > a[i + 1]:
			return i
	return -1
n = int(input())
a = [int(i) for i in input().split()]
ind = checkSort(a)
if ind == -1:
	print(0)
	exit(0)
newind = checkSort(a[ind + 1:])
if newind == -1 and a[-1] <= a[0]:
	print(n - ind - 1)
else:
	print(-1)


n = int(input())
arr = [int(x) for x in input().split()]
for i in range(1, n):
	if arr[i - 1] > arr[i]:
		if sorted(arr) == arr[i:] + arr[:i]:
			print(n - i)
			exit()
		else:
			print(-1)
			exit()
print(0)


n = int(input())
a = [int(x) for x in input().split()]
cnt = 0
pos = 0
for (x, y, i) in zip(a, a[1:] + [a[0]], range(n)):
	if x > y:
		cnt += 1
		pos = i
if cnt > 1:
	print(-1)
	exit(0)
if cnt == 0:
	print(0)
	exit(0)
print(n - pos - 1)


def arr_inp(n):
	if n == 1:
		return [int(x) for x in stdin.readline().split()]
	elif n == 2:
		return [float(x) for x in stdin.readline().split()]
	else:
		return [str(x) for x in stdin.readline().split()]
from sys import stdin
from collections import *
(n, a, ans) = (int(input()), deque(arr_inp(1)), 0)
if min(a) == max(a):
	ans = 0
else:
	for i in range(n):
		if a[-1] <= a[0]:
			ans += 1
			a.rotate(1)
		else:
			break
print(ans if a == deque(sorted(a.copy())) else -1)