#include <bits/stdc++.h>
using namespace std;
int n;
int len;
int ans = 1;
vector<vector<int> > v;
vector<int> indegree;
vector<bool> visited;
int gcd(int a, int b) {
  if (a < b) gcd(b, a);
  if (b == 0) return a;
  return gcd(b, a % b);
}
int lcm(int a, int b) { return a * (b / gcd(a, b)); }
void dfs(int now) {
  len++;
  visited[now] = true;
  for (int i = 0; i != v[now].size(); i++) {
    int next = v[now][i];
    if (!visited[next]) {
      dfs(next);
    }
  }
}
int main() {
  cin >> n;
  v.resize(n + 1);
  indegree.resize(n + 1, 0);
  visited.resize(n + 1, false);
  for (int i = 1; i <= n; i++) {
    int a;
    cin >> a;
    v[i].push_back(a);
    indegree[a]++;
  }
  for (int i = 1; i <= n; i++) {
    if (indegree[i] == 0) {
      cout << "-1\n";
      return 0;
    }
  }
  for (int i = 1; i <= n; i++) {
    if (!visited[i]) {
      len = 0;
      dfs(i);
      if (len % 2 == 0) len /= 2;
      ans = lcm(ans, len);
    }
  }
  cout << ans << endl;
  return 0;
}
