#include <bits/stdc++.h>
const int INF = 2147483647;
const long long MOD = 1e9 + 7;
using namespace std;
int n;
int gcd(int a, int b) {
  if (b > a) return gcd(b, a);
  while (b > 1) {
    int r = a % b;
    if (!r) return b;
    a = b;
    b = r;
  }
  return 1;
}
int lcm(int a, int b) { return a * b / gcd(a, b); }
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cin >> n;
  vector<int> vi(n + 1);
  for (int i = 1; i <= n; i++) {
    cin >> vi[i];
  }
  vector<bool> visited(n + 1, false);
  vector<int> cycleLengths;
  for (int i = 1; i <= n; i++) {
    int source = i;
    if (!visited[source]) {
      int cycleLength = 0;
      queue<int> q;
      q.push(source);
      while (!q.empty()) {
        int cur = q.front();
        visited[cur] = true;
        q.pop();
        if (!visited[vi[cur]]) {
          cycleLength++;
          q.push(vi[cur]);
        } else if (vi[cur] != source) {
          cout << -1;
          return 0;
        } else {
          cycleLength++;
        }
      }
      cycleLengths.push_back(cycleLength);
    }
  }
  vector<int> nums;
  for (int i : cycleLengths) {
    if (i == 0 || i == 2) {
      nums.push_back(1);
    } else if (i % 2) {
      nums.push_back(i);
    } else {
      nums.push_back(i / 2);
    }
  }
  int ans = nums[0];
  for (int i = 1; i < nums.size(); i++) {
    ans = lcm(ans, nums[i]);
  }
  cout << ans;
}
