#include <bits/stdc++.h>
using namespace std;
long Nod(long a, long b) {
  while (a && b)
    if (a >= b)
      a %= b;
    else
      b %= a;
  return a | b;
}
int main() {
  int n;
  cin >> n;
  vector<int> A(n, 0);
  for (int i = 0; i < n; i++) {
    cin >> A[i];
  }
  vector<int> B(n, 0);
  vector<int> C;
  int cv = 1;
  for (int i = 0; i < n; i++) {
    int l = 0;
    if (B[i] == 0) {
      int h = A[i] - 1;
      bool flag = true;
      for (; flag;) {
        int zh;
        if (B[h] == 0) {
          B[h] = cv;
          h = A[h] - 1;
          l++;
        } else
          flag = false;
      }
      cv++;
    }
    if (l > 0) C.push_back(l);
  }
  bool f1 = true;
  for (int i = 0; i < n; i++) {
    if (B[i] == 0) {
      f1 = false;
    }
  }
  if (!f1)
    cout << -1;
  else {
    for (int i = 0; i < C.size(); i++)
      if (C[i] % 2 == 0) C[i] /= 2;
    int k = C[0];
    for (int i = 1; i < C.size(); i++) {
      int h = 1;
      h = Nod(C[i], k);
      k = (C[i] * k) / h;
    }
    cout << k;
  }
}
