import sys from collections import defaultdict, deque n, k = map(int, input().split()) a = list(map(int, input().split())) b = sorted(a) # lưu vị trí của từng giá trị trong b pos = defaultdict(deque) for i in range(n): pos[b[i]].append(i) visited = [False]*n ans = 0 for i in range(n): if visited[i]: continue cycle = 0 j = i while not visited[j]: visited[j] = True val = a[j] target = pos[val].popleft() # nếu khác mod k thì impossible if target % k != j % k: print(-1) sys.exit() j = target cycle += 1 if cycle > 1: ans += cycle - 1 print(ans)