Put . This is the last occurrence time of the third most recently used color, or zero if fewer than three colors have appeared: the longest suffix using at most two colors starts immediately after that occurrence.
After a prefix ending at time , the newest color was used at . Let be the last occurrence time of the second-newest color, with when only one color has appeared. The value is prescribed, so is the only additional state needed for counting.
When appending position to a prefix ending at , there are three possibilities:
The third case strictly increases , because the second-newest occurrence is later than the third-newest. Therefore a flat report permits exactly the first two cases, while an increase permits only the third case and identifies its old state.
Let count prefixes in state and . Initially .
If , all old states survive once by repeating the newest color. The new state receives
because the one-color state has choices instead of one. Add this value to .
If , only the old state survives, and the new DP contains just
Clear old states with a cutoff index rather than repeatedly clearing the array. After this transition, only indices at least are active. Flat steps write fresh indices. A lookup below the cutoff is zero. The value remains until the first increase and is zero afterward.
Reject any for , or any decrease in . Other impossible profiles receive count zero through the transitions, including profiles with nondecreasing that cannot be realized. When , normalize modulo the prime; the correction on flat steps gives zero new two-color states.
Every extension falls into exactly one of the three cases, with the stated number of choices, so the transitions count every compatible sequence exactly once. The final sum is the answer.
Time and memory are per case. Reduce all counts modulo and use signed 64-bit intermediate products.