#include <bits/stdc++.h>
using namespace std;
int gcd(int a, int b) {
  if (a == b) {
    return a;
  }
  if (a % 2 == 0 && b % 2 == 0) {
    return 2 * gcd(a / 2, b / 2);
  }
  if (a % 2 == 0 && b % 2 != 0) {
    return gcd(a / 2, b);
  }
  if (a % 2 != 0 && b % 2 == 0) {
    return gcd(a, b / 2);
  }
  if (a % 2 != 0 && b % 2 != 0) {
    if (a > b) {
      return gcd((a - b) / 2, b);
    } else {
      return gcd(a, (b - a) / 2);
    }
  }
}
int lcm(int a, int b) { return a * b / (gcd(a, b)); }
int main(int argc, char const *argv[]) {
  int n;
  cin >> n;
  int A[n];
  int E[n];
  int C[n];
  int P[n];
  int a;
  for (int i = 0; i < n; ++i) {
    cin >> a;
    A[i] = a;
    E[i] = 0;
    P[i] = -1;
  }
  int count = 0;
  for (int i = 0; i < n; ++i) {
    if (!E[i]) {
      E[i] = 1;
      int k = A[i] - 1;
      for (int j = 0; j < n; ++j) {
        E[k] = 1;
        P[k] = i;
        if (i == k) {
          C[i] = j + 1;
          break;
        } else {
          k = A[k] - 1;
        }
      }
    }
  }
  sort(P, P + n);
  if (P[0] == -1) {
    cout << "-1";
    return 0;
  }
  int prev = P[0];
  int sum = C[P[0]];
  int result;
  if (C[P[0]] % 2 == 0) {
    result = C[P[0]] / 2;
  } else {
    result = C[P[0]];
  }
  for (int i = 1; i < n; ++i) {
    if (P[i] != prev) {
      if (C[P[i]] % 2 == 0) {
        result = lcm(result, C[P[i]] / 2);
      } else {
        result = lcm(result, C[P[i]]);
      }
      sum += C[P[i]];
      prev = P[i];
    }
  }
  if (sum == n) {
    cout << result;
  } else {
    cout << "-1";
  }
  return 0;
}
