#include <bits/stdc++.h>
using namespace std;
const int INF = 0x3f3f3f3f;
const long long LINF = 0x3f3f3f3f3f3f3f3fLL;
const double EPS = 1e-8;
const int MOD = 1000000007;
const int dy[] = {1, 0, -1, 0}, dx[] = {0, -1, 0, 1};
int main() {
  cin.tie(nullptr);
  ios::sync_with_stdio(false);
  int n;
  cin >> n;
  vector<int> a, ai(n);
  for (int i = (0); i < (n); ++i) cin >> ai[i];
  if (ai.front() == 1 && ai.back() == 1) {
    int idx;
    for (idx = n - 1; idx >= 0; --idx) {
      if (ai[idx] != 1) break;
    }
    for (int i = (idx + 1); i < (n); ++i) a.emplace_back(ai[i]);
    for (int i = (0); i < (idx + 1); ++i) a.emplace_back(ai[i]);
  } else {
    int idx;
    for (idx = 0; idx < n; ++idx) {
      if (ai[idx] == 1) break;
    }
    for (int i = (idx); i < (n); ++i) a.emplace_back(ai[i]);
    for (int i = (0); i < (idx); ++i) a.emplace_back(ai[i]);
  }
  int len = -1;
  for (int i = (0); i < (n); ++i) {
    if (a[i] != 1) {
      len = i;
      break;
    } else {
      len = 0;
    }
  }
  if (len == -1) {
    cout << 0 << '\n';
    return 0;
  }
  if (len == 0) {
    long long ans = 1;
    for (int i = (1); i < (n + 1); ++i) (ans *= i) %= MOD;
    cout << ans << '\n';
    return 0;
  }
  vector<pair<int, int> > exist(n + 1, {0, 0});
  exist[1] = {0, len};
  for (int i = len; i < n;) {
    if (exist[a[i]].second > 0) {
      cout << 0 << '\n';
      return 0;
    }
    exist[a[i]].first = i;
    int j = i;
    while (j < n && a[j] == a[i]) ++j;
    exist[a[i]].second = j - i;
    if (exist[a[i]].second > len) {
      cout << 0 << '\n';
      return 0;
    }
    i = j;
  }
  long long ans = 1;
  int can = 0;
  set<int> bigger, remain;
  for (int i = (0); i < (n); ++i) bigger.emplace(i);
  for (int i = (1); i < (n + 1); ++i) {
    if (exist[i].second == 0) {
      (ans *= can) %= MOD;
      --can;
    } else {
      if ((exist[i].first == 0 || a[exist[i].first - 1] > i) &&
          (exist[i].first + exist[i].second < n &&
           a[exist[i].first + exist[i].second] > i)) {
        if (exist[i].second != len) {
          cout << 0 << '\n';
          return 0;
        }
      }
      if ((exist[i].first - 1 >= 0 && a[exist[i].first - 1] < i) &&
          (exist[i].first + exist[i].second == n ||
           a[exist[i].first + exist[i].second] < i)) {
        (ans *= len - exist[i].second + 1) %= MOD;
      }
      for (int j = (exist[i].first); j < (exist[i].first + exist[i].second);
           ++j) {
        bigger.erase(j);
        remain.emplace(j);
      }
      auto it = remain.lower_bound(exist[i].first - len + 1);
      while (it != remain.end() && *it < exist[i].first + exist[i].second) {
        auto nearest = bigger.lower_bound(*it);
        if (nearest == bigger.end() || *nearest - *it >= len) {
          ++can;
          it = remain.erase(it);
        } else {
          it = remain.lower_bound(*nearest);
        }
      }
      --can;
    }
  }
  cout << ans << '\n';
  return 0;
}
