#include <bits/stdc++.h>
using namespace std;
int gcd(int a, int b) {
  if (a > b) swap(a, b);
  while (b) {
    int t = a % b;
    a = b;
    b = t;
  }
  return a;
}
int lcm(const vector<int> &a) {
  int res = a[0];
  for (int i = 1; i < a.size(); ++i) {
    res = res / gcd(res, a[i]) * a[i];
  }
  return res;
}
int main() {
  cin.sync_with_stdio(false);
  int n;
  cin >> n;
  vector<int> g(n, 0);
  for (int i = 0; i < n; ++i) {
    cin >> g[i];
    --g[i];
  }
  vector<int> cycles;
  vector<bool> visited(n, false);
  for (int i = 0; i < n; ++i) {
    if (!visited[i]) {
      int l = 0;
      int cur = i;
      bool failed = false;
      do {
        if (visited[cur]) {
          failed = true;
          break;
        }
        visited[cur] = true;
        cur = g[cur];
        ++l;
      } while (cur != i);
      if (failed) {
        cout << -1 << endl;
        return 0;
      }
      if (l % 2 == 0)
        cycles.push_back(l >> 1);
      else
        cycles.push_back(l);
    }
  }
  cout << lcm(cycles) << endl;
  return 0;
}
