#include <bits/stdc++.h>
using namespace std;
int vis[1000001];
int crush[1000001];
int cl;
int s[1000001];
int st, en;
void dfs(int i) {
  vis[i] = 1;
  cl++;
  if (!vis[crush[i]])
    dfs(crush[i]);
  else
    en = crush[i];
}
int gcd(int a, int b) {
  int temp;
  while (b > 0) {
    temp = b;
    b = a % b;
    a = temp;
  }
  return a;
}
int lcm(int a, int b) { return a * b / gcd(a, b); }
int main() {
  int n, i, j = 0, x, res, flag = 1;
  cin >> n;
  for (i = 0; i < n; i++) {
    cin >> x;
    crush[i] = x - 1;
  }
  for (i = 0; i < n; i++) {
    cl = 0;
    if (!vis[i]) {
      st = i;
      dfs(i);
      if (cl % 2 == 0)
        s[j++] = cl / 2;
      else
        s[j++] = cl;
    }
    if (st != en) {
      flag = 0;
      break;
    }
  }
  if (flag) {
    res = s[0];
    for (i = 1; i < j; i++) res = lcm(res, s[i]);
    cout << res << endl;
  } else
    cout << -1 << endl;
  return 0;
}
