Editorial
Suppose exactly bracket characters appear. Their positions can be chosen in ways, and each remaining position can contain any of the six non-bracket characters. The number of correct bracket strings on the chosen positions is the Catalan number
Therefore, if is the number of compilable strings of length ,
For a single test case, evaluating this sum directly gives an solution.
To handle all test cases efficiently, precompute every in linear time. Interpret [ as a step that increases the height by , ] as a step that decreases the height by , and each of the other six characters as a distinct step that keeps the height unchanged. A compilable string is exactly a weighted Motzkin path that never goes below height and ends at height .
Let
A first-step decomposition gives
so
Differentiating and rearranging gives
Comparing coefficients of yields, for ,
The required value is the probability
Dividing the recurrence by gives
with and .
Modulo , the numbers , , and every with are invertible. Hence the recurrence can be evaluated directly modulo the prime. If is the maximum input value, precompute once and answer each test case with .
The time complexity is and the space complexity is .
Before reduction, the probability has denominator . Therefore its reduced denominator is also coprime to .
Solution written by GPT5.6