KatInterview

Coin Flip Race: HHT vs HTH Probability and Conditional Wait

Arrays & HashingAuto-graded · 13 test cases
HardAuto-gradedArrays & Hashingmarkov-chainsprobabilityexpected-value

Last 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:

  1. Find P(W), the probability that HHT is completed first.
  2. Find E[N | W], the expected number of tosses given that HHT wins 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 HHT and HTH; 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].