Coin Flip Race: HHT vs HTH Probability and Conditional Wait
Arrays & HashingAuto-graded · 13 test casesLast updated
Tests whether you can set up a Markov chain for a pattern race, derive absorption probabilities, and compute a conditional expected stopping time.
Coin Flip Race: HHT vs HTH
A fair coin is tossed repeatedly. Each toss lands Heads (H) or Tails (T) with probability 1/2, independently of all previous tosses. The game ends the moment one of the following two length-3 patterns is completed:
- Pattern W:
HHT - Pattern L:
HTH
Let N be the total number of tosses when the game ends. Let W be the event that Pattern W is completed before Pattern L.
Your two tasks:
- Find P(W), the probability that
HHTis completed first. - Find E[N | W], the expected number of tosses given that
HHTwins the race.
Method Required
Model the process as a discrete-time Markov chain whose states capture the longest suffix of the toss history that matches a prefix of either target pattern. Use first-step analysis to find P(W) at every transient state, then compute the restricted expectation E[N · 1_W] via its own first-step recursion. Divide by P(W) to obtain the conditional expectation.
Output Format
Return a list of exactly two strings, each a fully reduced fraction "numerator/denominator":
- index 0:
P(W)as a reduced fraction - index 1:
E[N | W]as a reduced fraction
Constraints
- The coin is fair: P(H) = P(T) = 1/2 exactly.
- The two competing patterns are fixed as
HHTandHTH; no input is needed. - Both answers must be expressed as reduced fractions (e.g.,
"2/3", not"4/6"or"0.667"). - Absorption is guaranteed: the game ends with probability 1 in finite time.
Examples
Example 1
Input: hht_race_results()
Output: ['2/3', '19/3']
Hints
Hint 1
Draw the four transient states — call them S (start/reset), H, HH, and HT — and write down where each state goes on a Head and on a Tail. Notice that from HH, flipping another Head keeps you in HH (the last two flips are still HH), while flipping a Tail absorbs you into HHT immediately.
Hint 2
Once you see that HH always leads to HHT (never to HTH), write the first-step equations for p(s) = P(W | start at s). You will find p(HH) = 1 first, then express p(HT), p(H), and p(S) in terms of each other and solve the resulting linear system.
Hint 3
For the conditional expectation, define v(s) = E[N · 1_W | start at s]. The recursion is v(s) = p(s) + Σ_s' P(s→s') v(s'), not the plain expected-time recursion. The extra p(s) term accounts for the one flip just taken, weighted by the probability of eventually winning. Divide v(S) by p(S) to get E[N | W].
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Building the Markov Chain
At any point in the game, only the longest suffix of the flip history that matches a prefix of either HHT or HTH matters for the future. Everything else is forgotten. That gives four transient states:
- S — no useful suffix (the empty state, or after a dead-end
T) - H — last flip was
H - HH — last two flips were
HH - HT — last two flips were
HT
And two absorbing states: A (HHT completed) and B (HTH completed).
Transition table (each branch has probability 1/2):
| From | On H | On T |
|---|---|---|
| S | H | S |
| H | HH | HT |
| HH | HH | A |
| HT | B | S |
Two details worth noting:
- From HH, another
Hkeeps you in HH because the last two flips are stillHH. - From HT, a
Tresets to S becauseHTTshares no prefix with either pattern.
Part 1: P(W) via First-Step Analysis
Let p(s) = probability of absorbing into A from state s. Set p(A) = 1, p(B) = 0.
From the transitions above:
p(HH) = ½·p(HH) + ½·1→ p(HH) = 1. Once in HH, A is guaranteed — you just wait for the firstT.p(HT) = ½·0 + ½·p(S)=½ p(S)p(H) = ½·1 + ½·p(HT)=½ + ¼ p(S)p(S) = ½·p(H) + ½·p(S)→p(S) = p(H)
Substituting p(S) = p(H) into the expression for p(H):
p(H) = ½ + ¼ p(H) → ¾ p(H) = ½ → p(H) = 2/3
So p(S) = 2/3, p(HT) = 1/3, p(HH) = 1, and P(W) = 2/3.
Part 2: E[N | W] via Restricted Expectation
Define v(s) = E[N · 1_W | start at s]. This is the expected total tosses, counting only paths that end in A. The recursion is:
v(s) = p(s) + Σ_{s'} P(s → s') · v(s')
The p(s) term appears because every flip from s advances N by 1, but it only "counts" if the game ends in A — probability p(s).
Solving in order:
-
v(HH) = 1 + ½·v(HH)→ v(HH) = 2 -
v(HT) = 1/3 + ½·v(S) -
v(H) = 2/3 + ½·2 + ½·v(HT)=5/3 + ¼·v(S)(after substituting v(HT))Wait — more carefully:
v(H) = p(H) + ½·v(HH) + ½·v(HT)=2/3 + 1 + ½·v(HT). Withv(HT) = 1/3 + ½·v(S)this givesv(H) = 2/3 + 1 + 1/6 + ¼·v(S)=11/6 + ¼·v(S). -
v(S) = p(S) + ½·v(H) + ½·v(S)=2/3 + ½·v(H) + ½·v(S)→v(S) = 4/3 + v(H)
Substituting v(S) = 4/3 + v(H) into v(H) = 11/6 + ¼·v(S):
v(H) = 11/6 + ¼·(4/3 + v(H))
v(H) = 11/6 + 1/3 + ¼·v(H)
¾ v(H) = 13/6
v(H) = 26/9
Then v(S) = 4/3 + 26/9 = 38/9.
Finally:
E[N | W] = v(S) / p(S) = (38/9) / (2/3) = 19/3
Why This Is Correct
The state space is complete: every possible flip history maps to exactly one state, and the next state depends only on the current state plus the new flip. Absorption is certain because from any transient state there is a path of length at most 3 reaching an absorbing state. The v-recursion follows from the linearity of expectation: decompose E[N · 1_W] by the first flip and collect terms.
Common Pitfalls
- Wrong self-loop at HH. From HH, flipping
Hshould stay in HH (the suffix is stillHH), not move to H. Getting this wrong changesp(HH)from 1 and breaks all downstream values. - Using the plain expected-time recursion for v. Writing
v(s) = 1 + Σ P(s,s') v(s')is the unconditional recursion, not the restricted one. The correct recursion hasp(s)instead of1. - Computing E[N] and scaling.
E[N | W] ≠ E[N]. You needv(S) / p(S), notE[N]itself.
Complexity
The Markov chain has O(1) states (four transient + two absorbing). Building the transition table, setting up the linear system, and running Gaussian elimination are all O(1) in the size of the state space. With exact rational arithmetic via fractions.Fraction, the result is precise with no floating-point error.
Reference Solution
from fractions import Fraction
from typing import List
def hht_race_results() -> List[str]:
patterns = ("HHT", "HTH")
prefixes = {""}
for pattern in patterns:
prefixes.update(pattern[:i] for i in range(1, len(pattern)))
states = sorted(prefixes)
index = {state: i for i, state in enumerate(states)}
n = len(states)
transitions = [[None, None] for _ in states]
for state in states:
for coin_index, coin in enumerate("HT"):
text = state + coin
if text.endswith(patterns[0]):
transitions[index[state]][coin_index] = ("A", None)
elif text.endswith(patterns[1]):
transitions[index[state]][coin_index] = ("B", None)
else:
next_state = ""
for prefix in states:
if text.endswith(prefix) and len(prefix) > len(next_state):
next_state = prefix
transitions[index[state]][coin_index] = ("S", index[next_state])
# Build (I - Q) with two RHS columns:
# column n -> RHS for p(s) = P(absorb into A)
# column n+1 -> RHS for v(s) = E[N * 1_A]
matrix = [
[Fraction(int(i == j)) for j in range(n)] + [Fraction(0), Fraction(0)]
for i in range(n)
]
for i in range(n):
for outcome, target in transitions[i]:
if outcome == "S":
matrix[i][target] -= Fraction(1, 2)
elif outcome == "A":
matrix[i][n] += Fraction(1, 2)
def solve_column(rhs_column):
augmented = [row[:n] + [row[rhs_column]] for row in matrix]
for col in range(n):
pivot = next(r for r in range(col, n) if augmented[r][col])
augmented[col], augmented[pivot] = augmented[pivot], augmented[col]
divisor = augmented[col][col]
augmented[col] = [v / divisor for v in augmented[col]]
for r in range(n):
if r != col:
factor = augmented[r][col]
augmented[r] = [a - factor * b for a, b in zip(augmented[r], augmented[col])]
return [augmented[i][n] for i in range(n)]
# Step 1: solve for h = p(s)
h = solve_column(n)
# Step 2: build RHS for v(s); same (I-Q), new RHS derived from h
for i in range(n):
matrix[i][n + 1] = (
sum(
(h[target] / 2 for outcome, target in transitions[i] if outcome == "S"),
Fraction(0),
)
+ Fraction(sum(outcome == "A" for outcome, _ in transitions[i]), 2)
)
g = solve_column(n + 1)
probability = h[index[""]]
conditional_expectation = g[index[""]] / probability
return [
f"{probability.numerator}/{probability.denominator}",
f"{conditional_expectation.numerator}/{conditional_expectation.denominator}",
]