KatInterview

Expected Coin Flips to Observe Heads Then Tails

Arrays & HashingAuto-graded · 17 test cases
EasyAuto-gradedArrays & Hashingprobabilityexpected-valuemarkov-chains

Last updated

Tests ability to model a probabilistic process with states and solve expectation equations.

You repeatedly toss a fair coin. You stop as soon as you see Heads immediately followed by Tails (the pattern HT appearing in consecutive flips).

Write a function that returns the expected number of coin flips needed until this pattern first occurs.

Note: The answer should be computed analytically, not by simulation.

Constraints

  • The coin is fair: P(Heads) = P(Tails) = 0.5
  • Flips are independent
  • Return the exact expected value as a float

Examples

Example 1

Input: expected_flips_for_ht()

Output: 4

Example 2

Input: expected_flips_for_ht()

Output: 4

Hints

Hint 1

Track what matters: whether your most recent flip was Heads, since that determines how close you are to completing the pattern.

Hint 2

Set up equations for the expected flips remaining from each state. Remember to add 1 for the flip you're about to make.

Hint 3

Once you flip Heads, you stay one step away from finishing until you eventually flip Tails. What does that tell you about the expected wait from that state?