Same Tree, Different Order
The keys 1, 2, …, n are inserted into an initially empty binary search tree, one at a
time, using the textbook algorithm: to insert key x, start at the root and repeatedly
move to the left child if x is smaller than the current node's key or to the right
child if x is larger, until an empty spot is found, and put x there. No two keys are
ever equal, so this is always well defined.
You are given a permutation p of 1, …, n: key p_1 is inserted first, then p_2,
and so on up to p_n. This produces one specific tree shape.
Many different insertion orders can produce that exact same tree shape (the same root,
the same left and right child at every node). Count how many permutations of 1, …, n,
including p itself, build exactly that tree. Print the count modulo 10^9 + 7.
Input
The first line contains a single integer n (1 ≤ n ≤ 2·10^5).
The second line contains n distinct integers p_1, …, p_n (1 ≤ p_i ≤ n), a permutation
of 1, …, n.
Output
Print one integer: the number of permutations of 1, …, n that build the same binary
search tree as inserting p in order, modulo 10^9 + 7.
Notes
In the first example, p = (2, 1, 3). Inserting 2 first makes it the root; 1 then
becomes its left child and 3 its right child, regardless of which of 1 and 3 is
inserted next. So both (2, 1, 3) and (2, 3, 1) build the same tree, and no other
permutation does: the answer is 2.
In the second example, p = (3, 1, 2, 5, 4) builds a root 3 with left child 1 (whose
right child is 2) and right child 5 (whose left child is 4). Within the left part
{1, 2}, 1 must be inserted before 2; within the right part {4, 5}, 5 must be
inserted before 4. The only freedom is how the two parts, each with a fixed relative
order, are interleaved after the root, which can be done in C(4, 2) = 6 ways.