#include <bits/stdc++.h>
using namespace std;
long long nok(long long x, long long y) {
  if (x == 0 || y == 0) {
    return x + y;
  }
  if (x < y) {
    return nok(y, x);
  }
  return nok(y, x % y);
}
long long nod(long long x, long long y) { return x * y / nok(x, y); }
int main() {
  int n;
  cin >> n;
  vector<int> p(n);
  vector<int> ak(n);
  for (int i = 0; i < n; i++) {
    cin >> p[i];
    p[i]--;
    ak[p[i]]++;
  }
  for (int i = 0; i < n; i++) {
    if (ak[i] != 1) {
      cout << -1;
      return 0;
    }
  }
  vector<long long> len;
  vector<bool> col(n);
  for (int i = 0; i < n; i++) {
    if (!col[i]) {
      int v = p[i];
      int l = 1;
      int sv = i;
      while (v != sv) {
        col[v] = 1;
        v = p[v];
        l++;
      }
      if (l % 2 == 0) {
        len.push_back(l / 2);
      } else {
        len.push_back(l);
      }
    }
  }
  long long nood = 1;
  for (int i = 0; i < len.size(); i++) {
    nood = nod(nood, len[i]);
  }
  cout << nood;
}
