Problems > Ternary Strings Avoiding 22 > Editorial

Ternary Strings Avoiding 22 — Solution & Editorial

Back to the Problem

Model the count as a linear state transition (a fixed matrix acting on the current state vector) and raise the matrix to the N-th power in O(log N).

Complexity: O(log N)

Watch out: Track whether the string currently ends in 2; only then is the next 2 forbidden.