#include <bits/stdc++.h>
using namespace std;
const long long int inf = 99999999;
const long long int mod = 1000000007;
long long int minimum(long long int a, long long int b) {
  if (a < b) return a;
  return b;
}
long long int maximum(long long int a, long long int b) {
  if (a > b) return a;
  return b;
}
long long int power(long long int a, long long int b) {
  if (b == 0) return 1;
  long long int ans = power(a, b / 2);
  ans = (ans * ans) % mod;
  if (b % 2 == 1) ans = (ans * a) % mod;
  return ans;
}
long long int gcd(long long int a, long long int b) {
  if (b == 0) return a;
  return gcd(b, a % b);
}
long long int lcm(long long int a, long long int b) {
  return a * b / gcd(a, b);
}
int n;
vector<int> crush;
vector<bool> visited;
long long int ans;
bool possible;
void visit(int x) {
  vector<bool> onstack(n + 1, false);
  stack<int> st;
  vector<long long int> last_visit(n + 1, -1);
  int y = x;
  int stamp = 0;
  while (onstack[y] == false) {
    if (visited[y] == true) {
      possible = false;
      break;
    }
    last_visit[y] = stamp;
    st.push(y);
    onstack[y] = true;
    stamp++;
    y = crush[y];
  }
  if (possible) {
    long long int cycle = stamp - last_visit[y];
    if (cycle % 2 == 0) cycle /= 2;
    ans = lcm(cycle, ans);
    while (st.top() != y) {
      visited[st.top()] = true;
      st.pop();
    }
    visited[st.top()] = true;
    st.pop();
  }
  while (!st.empty()) {
    possible = false;
    visited[st.top()] = true;
    st.pop();
  }
}
int main() {
  cin >> n;
  crush = vector<int>(n + 1);
  visited = vector<bool>(n + 1, false);
  ans = 1;
  possible = true;
  int i;
  for (i = 1; i <= n; i++) cin >> crush[i];
  for (i = 1; i <= n; i++) {
    if (!possible) break;
    if (!visited[i]) visit(i);
  }
  if (!possible)
    cout << "-1" << endl;
  else
    cout << ans << endl;
}
