#include <bits/stdc++.h>
static bool detect_loops(const std::vector<int> &p, std::vector<int> &loops) {
  std::vector<int> visited(p.size(), -1);
  for (int i = 0; i != (int)p.size(); ++i) {
    if (visited[i] != -1) continue;
    int size = 1;
    int s = i;
    visited[s] = s;
    while (visited[p[s]] == -1) {
      visited[p[s]] = visited[s];
      s = p[s];
      ++size;
    }
    if (p[s] != i) return false;
    loops.push_back(size);
  }
  return true;
}
static unsigned long long gcd(unsigned long long a, unsigned long long b) {
  while (a && b) {
    const unsigned long long tmp = a;
    a = b;
    b = tmp % b;
  }
  return a + b;
}
static unsigned long long lcm(unsigned long long a, unsigned long long b) {
  return (a * b) / gcd(a, b);
}
int main() {
  std::ios_base::sync_with_stdio(false);
  int n;
  std::cin >> n;
  std::vector<int> crush(n);
  for (int i = 0; i != n; ++i) {
    int x;
    std::cin >> x;
    crush[i] = x - 1;
  }
  std::vector<int> loops;
  if (!detect_loops(crush, loops)) {
    std::cout << "-1\n";
    return 0;
  }
  for (int i = 0; i != (int)loops.size(); ++i)
    if (loops[i] % 2 == 0) loops[i] /= 2;
  unsigned long long ans = loops[0];
  for (int i = 0; i != (int)loops.size(); ++i) ans = lcm(ans, loops[i]);
  std::cout << ans << "\n";
  return 0;
}
