#include <bits/stdc++.h>
using namespace std;
const double PI = acos(-1.0);
template <typename T, typename TT>
void debug(T a[], TT n) {
  for (TT i = 0; i < n; i++) cout << a[i] << " ";
  printf("\n");
}
int inline set_bit(int mask, int i) { return mask = mask | (1 << i); }
int inline reset_bit(int mask, int i) { return mask = mask & ~(1 << i); }
bool inline check_bit(int mask, int i) { return mask & (1 << i); }
long long inline gcd(long long a, long long b) {
  return !b ? abs(a) : gcd(b, a % b);
}
long long inline lcm(long long a, long long b) { return (a / gcd(a, b) * b); }
long long bigmod(long long a, long long b, long long m) {
  if (!b) {
    return 1 % m;
  }
  if (b % 2) {
    return (a % m * bigmod(a, b - 1, m)) % m;
  } else {
    long long x = bigmod(a, b / 2, m) % m;
    return (x * x) % m;
  }
}
long long power(long long a, long long b) {
  if (!b) {
    return 1;
  }
  if (b % 2) {
    return a * power(a, b - 1);
  } else {
    long long x = power(a, b / 2);
    return x * x;
  }
}
double cartesian_dist(double x1, double y1, double x2, double y2) {
  return sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
}
double trngl_area1(double a, double b, double c) {
  double s = (a + b + c) / 2.0;
  return sqrt(s * (s - a) * (s - b) * (s - c));
}
double trngl_area2(double x1, double y1, double x2, double y2, double x3,
                   double y3) {
  return .5 * (x1 * (y2 - y3) - x2 * (y1 - y3) + x3 * y1 - y2);
}
const double EPS = 10E-7;
void dfs(int u, vector<int> vec[], char *vis, stack<int> &st) {
  vis[u] = 1;
  for (int i = 0; i < vec[u].size(); i++)
    if (!vis[vec[u][i]]) dfs(vec[u][i], vec, vis, st);
  st.push(u);
}
void dfs2(int u, vector<int> r_vec[], char vis[], int cnt, vector<int> ans[]) {
  ans[cnt].push_back(u);
  vis[u] = 1;
  for (int i = 0; i < r_vec[u].size(); i++)
    if (!vis[r_vec[u][i]]) dfs2(r_vec[u][i], r_vec, vis, cnt, ans);
}
void SSC(vector<int> vec[], int n, vector<int> r_vec[], int *arr) {
  char vis[n + 2];
  memset(vis, 0, sizeof(vis));
  stack<int> st;
  for (int i = 1; i <= n; i++)
    if (!vis[i]) dfs(i, vec, vis, st);
  vector<int> ans[n + 2];
  int cnt = 0, z;
  memset(vis, 0, sizeof(vis));
  while (!st.empty()) {
    z = st.top();
    st.pop();
    if (!vis[z]) {
      cnt++;
      dfs2(z, r_vec, vis, cnt, ans);
    }
  }
  int res = 1;
  for (int i = 1; i <= cnt; i++) {
    int z = ans[i].size();
    if (z == 1) {
      if (ans[i][0] != arr[ans[i][0]]) {
        res = -1;
        break;
      }
    } else if (z % 2 == 0)
      res = lcm(res, z / 2);
    else if (z % 2 == 1)
      res = lcm(res, z);
  }
  printf("%d", res);
  printf("\n");
}
int main() {
  int n, num;
  while (1 == scanf("%d", &n)) {
    vector<int> vec[n + 5];
    vector<int> r_vec[n + 5];
    int arr[n + 5];
    for (int i = 1; i <= n; i++) {
      scanf("%d", &num);
      arr[i] = num;
      vec[i].push_back(num);
      r_vec[num].push_back(i);
    }
    SSC(vec, n, r_vec, arr);
  }
  return 0;
}
