#include <bits/stdc++.h>
using namespace std;
vector<long long> cr, vis;
long long dfs(long long start, long long now, long long len) {
  vis[now] = 1;
  if (cr[now] == start) return len;
  if (vis[cr[now]]) return -1;
  return dfs(start, cr[now], len + 1);
}
long long mygcd(long long a, long long b) {
  while (true) {
    if (a == 0) return b;
    if (b == 0) return a;
    long long tmp = a;
    a = b;
    b = tmp % b;
  }
}
long long mylcm(long long a, long long b) { return (a * b) / mygcd(a, b); }
int main() {
  long long n;
  cin >> n;
  cr.resize(n);
  vis.resize(n);
  for (long long i = 0; i < n; i++) {
    cin >> cr[i];
    cr[i]--;
    vis[i] = 0;
  }
  vector<long long> cycl;
  for (long long i = 0; i < n; i++) {
    if (vis[i] == 0) {
      long long tmp = dfs(i, i, 1);
      if (tmp == -1) {
        cout << -1;
        return 0;
      }
      if (tmp % 2 == 0)
        cycl.push_back(tmp / 2);
      else
        cycl.push_back(tmp);
    }
  }
  long long cnt_lcm = 1;
  for (long long i = 0; i < cycl.size(); i++) cnt_lcm = mylcm(cnt_lcm, cycl[i]);
  cout << cnt_lcm;
  return 0;
}
