TITLE: a question related to two competing patterns in coin tossing
QUESTION [6 upvotes]: If I have a two-sided coin with probability $p$ showing head. I repeatedly toss it until either HTHTH or HTHH appears. Can you calculate 
1) the probability when I got HTHTH, and 
2) the expected value of the number of tosses before I stop?
Thanks.

REPLY [5 votes]: There is a direct, and rather automatic, way to compute the probability to hit A=HTHTH first rather than B=HTHH. 
Both motives begin by HTH hence one can wait until HTH first appears. Then, either (1) the next letter is H, or (2) the two next letters are TH, or (3) the two next letters are TT. If (1) happens, B won. If (2) happens, A won. If (3) happens, one has to wait for more letters to know who won. The important fact in case (3) is that, since the last letters are TT, A or B must be entirely produced again. 
Hence, $p_B=p_1+p_3p_B$ and $p_A=p_2+p_3p_A$, where $p_i$ for $i=$ 1, 2 and 3, is a shorthand for the conditional probability that ($i$) happens starting from the word HTH. Since $p_1=p$, $p_2=qp$ and $p_3=q^2$, one gets $p_B=p_1/(1-p_3)=p/(1-q^2)$, hence
$$
p_B=1/(1+q),\quad p_A=q/(1+q).
$$
Similarly, a standard, and rather automatic, way to compute the mean number of tosses before this happens is to consider a Markov chain on the state space made of the prefixes of the words one wishes to complete. 
Here, the states are 0 (for the empty prefix), 1=H, 2=HT, 3=HTH, B=HTHH, 4=HTHT and A=HTHTH. The transitions are from 0 to 1 and 0, from 1 to 2 and 1, from 2 to 3 and 0, from 3 to B and 4 and from 4 to A and 0. The transitions from B and from A are irrelevant. The next step is to compute $n_s$ the number of tosses needed to produce A or B starting from any state $s$ amongst 0, 1, 2, 3 and 4, knowing that one is in fact only interested in $n_0$. 
The $n_s$ are solutions of a Cramér system which reflects the structure of the underlying Markov chain: 
$$
n_0=1+pn_1+qn_0,\quad n_1=1+pn_1+qn_2,\quad n_2=1+pn_3+qn_0,
$$ 
$$
n_3=1+qn_4,\quad n_4=1+qn_0.
$$
Solving this system of equations backwards, that is, going from the last equation back to the first one, yields $n_3$ in terms of $n_0$, then $n_2$ in terms of $n_0$, then $n_1$ in terms of $n_0$, and finally an equation for $n_0$ alone, which yields Mike's formula for $n_0$, namely:
$$
n_0=\frac{1+pq+p^2q+p^2q^2}{p^3q(1+q)}.
$$
An accessible reference for these techniques (in the context of genomic sequence analysis) is the book DNA, Words and Models by Robin, Rodolphe and Schbath, at Cambridge UP.