#include <bits/stdc++.h>
using namespace std;
long long gcd(long long a, long long b) {
  if (b == 0) return a;
  return gcd(b, a % b);
}
long long findlcm(vector<long long> &arr, long long n) {
  long long ans = arr[0];
  for (long long i = 1; i < n; i++)
    ans = (((arr[i] * ans)) / (gcd(arr[i], ans)));
  return ans;
}
int main() {
  long long n;
  cin >> n;
  long long arr[n + 1];
  bool visited[n + 1];
  for (int i = 1; i < n + 1; i++) {
    visited[i] = false;
    cin >> arr[i];
    arr[i];
  }
  vector<long long> ar1;
  for (int i = 1; i <= n; i++) {
    long long a = i;
    long long c = 0;
    while (visited[a] == false) {
      visited[a] = true;
      a = arr[a];
      if (visited[a] == true && a != i) {
        cout << -1;
        return 0;
      }
      c++;
    }
    if (c != 0) {
      if (c % 2 == 0)
        ar1.push_back(c / 2);
      else
        ar1.push_back(c);
    }
  }
  cout << findlcm(ar1, ar1.size());
  return 0;
}
