TITLE: Recursion problem - ternary words not containing 121
QUESTION [9 upvotes]: How many ternary words in seven letters do not contain the word $121$?

My naive approach is:

If starts with 2 or 3, move to $T(n-1)$
If starts with 12, move to $T(n-3)$
If starts with 13, move to $T(n-2)$

But what if we start with $11$? I've seen some techniques using two recursive sequences...

REPLY [2 votes]: This answer is based upon the Goulden-Jackson Cluster Method.

We consider the set words of length $n\geq 0$ built from an alphabet $$\mathcal{V}=\{0,1,2\}$$ and the set $B=\{121\}$ of bad words, which are not allowed to be part of the words we are looking for. We derive a generating function $f(s)$ with the coefficient of $s^n$ being  the number of searched words of length $n$.

According to the paper (p.7) the generating function $f(s)$  is
\begin{align*}
f(s)=\frac{1}{1-ds-\text{weight}(\mathcal{C})}\tag{1}
\end{align*}
with $d=|\mathcal{V}|=3$, the size of the alphabet and $\mathcal{C}$ the weight-numerator of bad words with
\begin{align*}
\text{weight}(\mathcal{C})=\text{weight}(\mathcal{C}[121])
\end{align*}
We calculate according to the paper
\begin{align*}
\text{weight}(\mathcal{C}[121])&=-s^3-s^2\text{weight}(\mathcal{C}[121])\\
\end{align*}
and get
\begin{align*}
\text{weight}(\mathcal{C})=-\frac{s^3}{1+s^2}
\end{align*}

It    follows
\begin{align*}
f(s)&=\frac{1}{1-ds-\text{weight}(\mathcal{C})}\\
&=\frac{1}{1-3s+\frac{s^3}{1+s^2}}\\
&=\frac{1+s^2}{1-3s+s^2-2s^3}\\
&=1+3s+9s^2+26s^3+\color{blue}{75}s^4+217s^5+628s^6\\
&\qquad+\color{red}{1817}s^7+5257s^8+15210s^9+44007s^{10}+\cdots
\end{align*}
The last line was calculated with the help of Wolfram Alpha. We see   the number of valid words from the alphabet $\{0,1,2\}$ of length $7$ which do not contain the word $121$ is $\color{red}{1817}$.

So, e.g. out of $3^4=81$ ternary  words of length $4$ there are $\color{blue}{75}$ valid words and $6$ invalid words marked blue in the table below.
\begin{array}{ccccccccc}
0000&0100&0200&1000&1100&1200&2000&2100&2200\\
0001&0101&0201&1001&1101&1201&2001&2101&2201\\
0002&0102&0202&1002&1102&1202&2002&2102&2202\\
0010&0110&0210&1010&1110&\color{blue}{1210}&2010&2110&2210\\
0011&0111&0211&1011&1111&\color{blue}{1211}&2011&2111&2211\\
0012&0112&0212&1012&1112&\color{blue}{1212}&2012&2112&2212\\
0020&0120&0220&1020&1120&1220&2020&2120&2220\\
0021&\color{blue}{0121}&0221&1021&\color{blue}{1121}&1221&2021&\color{blue}{2121}&2221\\
0022&0122&0222&1022&1122&1222&2022&2122&2222\\
\end{array}