Problem:
Score : 900 points

Problem Statement

You are given a sequence of N integers: A_1,A_2,...,A_N.

Find the number of permutations p_1,p_2,...,p_N of 1,2,...,N that can be changed to A_1,A_2,...,A_N by performing the following operation some number of times (possibly zero), modulo 998244353:

For each 1\leq i\leq N, let q_i=min(p_{i-1},p_{i}), where p_0=p_N. Replace the sequence p with the sequence q.

Constraints

1 \leq N \leq 3 × 10^5

1 \leq A_i \leq N

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1
:
A_N

Output

Print the number of the sequences that satisfy the condition, modulo 998244353.

Sample Input 1

3
1
2
1

Sample Output 1

2

(2,3,1) and (3,2,1) satisfy the condition.

Sample Input 2

5
3
1
4
1
5

Sample Output 2

0

Sample Input 3

8
4
4
4
1
1
1
2
2

Sample Output 3

24

Sample Input 4

6
1
1
6
2
2
2

Sample Output 4

0

Solution in Rust (1.15.1) (judge verdict: Runtime Error)

// ---------- begin ModInt ----------
const MOD: u32 = 998_244_353;

#[derive(Clone, Copy)]
struct ModInt(u32);

impl std::ops::Add for ModInt {
    type Output = ModInt;
    fn add(self, rhs: ModInt) -> Self::Output {
        let mut d = self.0 + rhs.0;
        if d >= MOD {
            d -= MOD;
        }
        ModInt(d)
    }
}

impl std::ops::AddAssign for ModInt {
    fn add_assign(&mut self, rhs: ModInt) {
        *self = *self + rhs;
    }
}

impl std::ops::Sub for ModInt {
    type Output = ModInt;
    fn sub(self, rhs: ModInt) -> Self::Output {
        let mut d = self.0 + MOD - rhs.0;
        if d >= MOD {
            d -= MOD;
        }
        ModInt(d)
    }
}

impl std::ops::SubAssign for ModInt {
    fn sub_assign(&mut self, rhs: ModInt) {
        *self = *self - rhs;
    }
}

impl std::ops::Mul for ModInt {
    type Output = ModInt;
    fn mul(self, rhs: ModInt) -> Self::Output {
        ModInt((self.0 as u64 * rhs.0 as u64 % MOD as u64) as u32)
    }
}

impl std::ops::MulAssign for ModInt {
    fn mul_assign(&mut self, rhs: ModInt) {
        *self = *self * rhs;
    }
}

impl std::ops::Neg for ModInt {
    type Output = ModInt;
    fn neg(self) -> Self::Output {
        ModInt(if self.0 == 0 {0} else {MOD - self.0})
    }
}

impl std::fmt::Display for ModInt {
    fn fmt<'a>(&self, f: &mut std::fmt::Formatter<'a>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl std::str::FromStr for ModInt {
    type Err = std::num::ParseIntError;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let val = s.parse::<u32>()?;
        Ok(ModInt::new(val))
    }
}

#[allow(dead_code)]
impl ModInt {
    pub fn new(n: u32) -> ModInt {
        ModInt(n % MOD)
    }
    pub fn zero() -> ModInt {
        ModInt(0)
    }
    pub fn one() -> ModInt {
        ModInt(1)
    }
    pub fn pow(self, mut n: u32) -> ModInt {
        let mut t = ModInt::one();
        let mut s = self;
        while n > 0 {
            if n & 1 == 1 {
                t *= s;
            }
            s *= s;
            n >>= 1;
        }
        t
    }
    pub fn inv(self) -> ModInt {
        self.pow(MOD - 2)
    }
}
// ---------- end ModInt ----------
//https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8 より
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
    ($($r:tt)*) => {
        let s = {
            use std::io::Read;
            let mut s = String::new();
            std::io::stdin().read_to_string(&mut s).unwrap();
            s
        };
        let mut iter = s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
}

macro_rules! input_inner {
    ($iter:expr) => {};
    ($iter:expr, ) => {};
    ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {
        let $var = read_value!($iter, $t);
        input_inner!{$iter $($r)*}
    };
}

macro_rules! read_value {
    ($iter:expr, ( $($t:tt),* )) => {
        ( $(read_value!($iter, $t)),* )
    };
    ($iter:expr, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($iter, $t)).collect::<Vec<_>>()
    };
    ($iter:expr, chars) => {
        read_value!($iter, String).chars().collect::<Vec<char>>()
    };
    ($iter:expr, usize1) => {
        read_value!($iter, usize) - 1
    };
    ($iter:expr, $t:ty) => {
        $iter.next().unwrap().parse::<$t>().expect("Parse error")
    };
}

//

// 1がないなら0
// 連続した固まりじゃない数字があったら0
// 連続した固まりの時、その1のサイズが操作回数
// 1のサイズより大きい固まりあったら0
// また1の位置も確定する
// 全部1なら(N-1)!
// 操作回数kとする
// 操作前の配列をA, 操作後の配列をBとおく
// また添字はmodを取るものとする
// b[i] < b[i + 1] なら
// a[i - k] = b[i]
// b[i] > b[i + 1] なら
// a[i + 1] = b[i + 1]
// 遷移から
// a[i] >= max(b[i - k]..b[i]) となるはず

fn run() {
    input! {
        n: usize,
        b: [usize1; n],
    }
    let mut width = vec![0; n];
    for i in 0..n {
        if b[i] == b[(i + n - 1) % n] {
            continue;
        }
        let v = b[i];
        if width[v] > 0 {// 固まりが2つ以上
            println!("0");
            return;
        }
        width[v] = 1;
        let mut j = (i + 1) % n;
        while j != i && b[j] == v {
            j = (j + 1) % n;
            width[v] += 1;
        }
    }
    let step = width[0] - 1;
    if *width.iter().max().unwrap() > step + 1 {
        println!("0");
        return;
    }
    let ini = std::usize::MAX;
    let mut used = vec![false; n];
    let mut assign = vec![ini; n];
    for i in 0..n {
        let r = (i + 1) % n;
        if b[i] < b[r] {
            let x = (i - step + n) % n;
            if (assign[x] != ini && assign[x] != b[i]) || (assign[x] == ini && used[b[i]]) {
                println!("0");
                return;
            }
            used[b[i]] = true;
            assign[x] = b[i];
        }
        if b[i] > b[r] {
            if (assign[r] != ini && assign[r] != b[r]) || (assign[r] == ini && used[b[r]]) {
                println!("0");
                return;
            }
            used[b[r]] = true;
            assign[r] = b[r];
        }
    }
    let mut deq = std::collections::VecDeque::<(usize, usize)>::new();
    for i in (0..n).rev() {
        let v = b[i];
        while deq.len() > 0 && deq.back().unwrap().0 <= v {
            deq.pop_back();
        }
        deq.push_back((v, i + n));
    }
    let mut cnt = vec![ModInt::zero(); n + 1];
    for i in (0..n).rev() {
        let v = b[i];
        while deq.len() > 0 && deq.back().unwrap().0 <= v {
            deq.pop_back();
        }
        deq.push_back((v, i));
        while deq.front().unwrap().1 > i + step {
            deq.pop_front();
        }
        let f = deq.front().unwrap().0;
        if assign[i] == ini {
            cnt[f] += ModInt::one();
        } else if assign[i] != f {
            println!("0");
            return;
        }
    }
    let mut ans = ModInt::one();
    let mut rem = ModInt::zero();
    for i in 0..n {
        rem += cnt[i];
        if !used[i] {
            if width[i] > 0 {
                ans *= ModInt((step + 2 - width[i]) as u32);
            } else {
                ans *= rem;
            }
            rem -= ModInt::one();
        }
    }
    println!("{}", ans);
}

fn main() {
    run();
}