#include<bits/stdc++.h>
#define to edge[i].v
#define mp make_pair
#define rint register int
#define debug(x) cerr<<#x<<"="<<x<<endl
#define fgx cerr<<"-------------"<<endl
#define N 1000000
using namespace std;
typedef long long ll;
typedef long double db;
typedef pair<int,int> pii;
const int mod=1e9+7;
int fa[N],s[N],vis[N],go[N];
struct gg{int l,r,v,id,pre,nxt,len,sz,qaq;}a[N];
int findfa(int x){return fa[x]==x?x:fa[x]=findfa(fa[x]);}
inline bool cmp(gg x,gg y){return x.v<y.v;}
int main()
{//	freopen("a.in","r",stdin);
//	freopen("a.out","w",stdout);
	int n,t=0,k=-233,ans=1,num=0,fac=1; cin>>n;
	for(rint i=1;i<=n;i++) scanf("%d",&s[i]),fac=(ll)fac*i%mod,s[i+n]=s[i]; s[0]=s[n];
	for(rint i=0;i<n;i++)
	if(s[i]!=s[i+1]){for(rint j=1;j<=n;j++)s[j]=s[j+i];break;}
//	for(rint i=1;i<=n;i++) cerr<<s[i]<<",";fgx;
	for(rint i=1,j;i<=n;i=j)
	{	for(j=i+1;j<=n&&s[i]==s[j];j++);
	//	debug(i);debug(j);
		a[++t].v=s[i]; a[t].id=t; a[t].l=i; a[t].r=j-1; a[t].len=a[t].r-a[t].l+1;
		if(vis[s[i]]) return !printf("0"); vis[s[i]]=1; if(s[i]==1) k=a[t].r-a[t].l;
	}//fgx;
	a[0]=a[t]; a[t+1]=a[1];
	for(rint i=1;i<=t;i++) a[i].pre=a[i-1].v,a[i].nxt=a[i+1].v;
	if(t==1) return a[1].v==1?!printf("%d",fac):!printf("0");
	if(k==-233) return !printf("0"); sort(a+1,a+t+1,cmp);
	for(rint i=1;i<=t;i++) if(a[i].r-a[i].l>k) return !printf("0");
	for(rint i=1;i<=t;i++) go[a[i].id]=i,a[i].sz=1; go[0]=go[t]; go[t+1]=go[1];
	for(rint i=1;i<=t;i++)
	{	if(a[i].pre>a[i].v&&a[i].nxt>a[i].v)
		{if(a[i].r-a[i].l!=k)return !printf("0");}
		if(a[i].pre>a[i].v){a[i].len--;continue;}
		else if(a[i].nxt>a[i].v){a[go[a[i].id-1]].len--;continue;}
		else ans=(ll)ans*(a[i].l-(a[i].r-k)+1)%mod,a[i].qaq=1;
	}//debug(ans);
	for(rint i=1;i<=t;i++) fa[i]=i;
	for(rint i=1,j=1;i<=n;i++)
	{	if(a[j].v==i)
		{	int l=findfa(go[a[j].id-1]),r=findfa(go[a[j].id+1]),cur=findfa(j);
		//	debug(a[cur].len);debug(l);debug(a[l].len);debug(num);
			if(a[l].v<a[j].v)
			num-=max(0,a[l].len-k),a[cur].len+=a[l].len,a[cur].sz+=a[l].sz,fa[l]=cur;
			if(l!=r&&a[r].v<a[j].v)
			num-=max(0,a[r].len-k),a[cur].len+=a[r].len,a[cur].sz+=a[r].sz,fa[r]=cur;
			num+=max(0,a[cur].len-k); num-=a[cur].qaq; j++;
			if(a[cur].sz==t) num+=k;
		//	debug(a[cur].len);
		}
		else ans=(ll)ans*num%mod,num--;
	}
	cout<<ans;
	return 0;
}
