#include <bits/stdc++.h>
using namespace std;
long long int arr[1000001];
vector<int> g1[300005], g2[300005];
bool visited1[300005], visited2[300005];
stack<int> s, s2;
long long int gcd(long long int a, long long int b) {
  if (b == 0)
    return a;
  else
    return gcd(b, a % b);
}
void dfs1(int v) {
  visited1[v] = true;
  for (int i = 0; i < g1[v].size(); i++) {
    if (visited1[g1[v][i]] == false) {
      dfs1(g1[v][i]);
    }
  }
  s.push(v);
}
void dfs2(int v) {
  visited2[v] = true;
  s2.push(v);
  for (int i = 0; i < g2[v].size(); i++) {
    if (visited2[g2[v][i]] == false) {
      dfs2(g2[v][i]);
    }
  }
}
int main() {
  ios::sync_with_stdio(false);
  cin.clear();
  long long int t, n, i, j, ans = 1, flag = 0, count = 0, sum = 0, k, m, u, v;
  cin >> n;
  for (i = 1; i <= n; i++) {
    cin >> u;
    arr[u] = 1;
    g1[i].push_back(u);
    g2[u].push_back(i);
  }
  for (i = 1; i <= n; i++) {
    if (arr[i] == 0) {
      cout << -1;
      return 0;
    }
  }
  if (n == 1) {
    cout << 1;
    return 0;
  }
  for (i = 1; i <= n; i++) {
    if (visited1[i] == false) {
      dfs1(i);
    }
  }
  while (!s.empty()) {
    if (visited2[s.top()] == false) {
      dfs2(s.top());
      if (s2.size() % 2)
        m = s2.size();
      else
        m = s2.size() / 2;
      k = (ans * m) / gcd(ans, m);
      ans = k;
    }
    while (!s2.empty()) s2.pop();
    s.pop();
  }
  cout << ans;
}
