If , each winner is a different element of the permutation, so the answer is .
Now assume . If , there is one segment and every permutation is valid. Otherwise, every interior position belongs to at least two length- segments. Placing the global minimum at such a position would give those segments the same winner. Therefore the minimum must be at one of the two ends.
At an end, the minimum belongs to exactly one length- segment. Remove that minimum. All other segments are precisely the length- segments of the remaining row, and none can have the removed value as a winner. Consequently, the original permutation is valid if and only if the remaining permutation is valid.
Repeat until elements remain. Each of the removed minima has two choices of end, and the final values can appear in any of orders. Reversing the removals reconstructs one distinct permutation from each sequence of choices, so this counts every valid permutation exactly once:
Precompute factorials and powers of two modulo up to the maximum allowed . Answer each test case in time. Total time is and memory is ; there is no restriction on and no per-case linear scan is needed. Use 64-bit intermediate products before taking the modulus.