#include <bits/stdc++.h>
using namespace std;
int n, tmp;
vector<int> delka;
int first;
vector<vector<int>> v;
vector<int> nasobky;
int lms(int n1, int n2) {
  int maxx = (n1 > n2) ? n1 : n2;
  do {
    if (maxx % n1 == 0 && maxx % n2 == 0) {
      break;
    } else {
      maxx++;
    }
  } while (true);
  return maxx;
}
int main() {
  ios::sync_with_stdio(0);
  cin >> n;
  for (int i = 0; i < n; i++) {
    vector<int> tmpV;
    cin >> tmp;
    v.push_back(tmpV);
    v[v.size() - 1].push_back(tmp);
    delka.push_back(0);
  }
  deque<int> q;
  q.push_back(0);
  int cnt = 0;
  first = cnt;
  bool foundCycle = false;
  while (cnt != v.size()) {
    tmp = 0;
    foundCycle = false;
    while (!q.empty()) {
      for (int j = 0; j < 1; j++) {
        if (v[q.front()][0] - 1 == first) {
          foundCycle = true;
        } else if (v[q.front()][0] - 1 != q.front()) {
          q.push_back(v[q.front()][0] - 1);
        }
      }
      q.pop_front();
      tmp++;
      if (tmp > v.size()) {
        q.clear();
        tmp = -1;
        break;
      }
    }
    if (!foundCycle) {
      tmp = -1;
    }
    if (tmp % 2 == 0 && tmp >= 0) {
      tmp /= 2;
    }
    nasobky.push_back(tmp);
    delka[cnt] = tmp;
    cnt++;
    for (int j = cnt; j < v.size(); j++) {
      if (!v[j].empty()) {
        q.push_back(j);
        first = j;
        break;
      }
    }
  }
  for (int i = 0; i < n; i++) {
    if (delka[i] < 0) {
      cout << "-1" << endl;
      return 0;
    }
  }
  if (nasobky.size() == 1) {
    cout << nasobky.front() << endl;
  } else if (nasobky.size() == 2) {
    cout << lms(nasobky.front(), nasobky.back());
  } else {
    int tmpLMS = lms(nasobky[0], nasobky[1]);
    for (int i = 2; i < nasobky.size(); i++) {
      tmpLMS = lms(tmpLMS, nasobky[i]);
    }
    cout << tmpLMS << endl;
  }
  return 0;
}
