#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e5 + 5;
int n, m, a[maxn], vis[maxn];
vector<int> g[maxn];
int cc, len;
long long gcd(long long a, long long b) { return (!b) ? a : gcd(b, a % b); }
long long lcm(long long a, long long b) { return a / gcd(a, b) * b; }
void solve() {
  memset(vis, 0, sizeof(vis));
  long long ans = 1LL;
  for (int i = 1; i <= n; i++) {
    if (!vis[i]) {
      int st = i, len = 0, now = i;
      while (!vis[now]) {
        vis[now] = 1;
        now = a[now];
        len++;
        if (now == st) break;
      }
      if (now != st) {
        puts("-1");
        return;
      }
      if (len % 2 == 0) len = len / 2;
      ans = lcm(ans, len);
    }
  }
  printf("%I64d\n", ans);
}
int main() {
  while (scanf("%d", &n) != EOF) {
    for (int i = 1; i <= n; i++) g[i].clear();
    for (int i = 1; i <= n; i++) scanf("%d", &a[i]);
    solve();
  }
  return 0;
}
