Expected Tosses for Consecutive Heads-Tails

Easy · Statistics & Math · Data Scientist · Technical Screen

Problem Statement

An unbiased coin—landing Heads (H) with probability 0.5 and Tails (T) with probability 0.5 independently on each toss—is tossed repeatedly until a Heads outcome is immediately followed on the very next toss by a Tails outcome, completing the contiguous two-toss pattern HT.

Compute and return the exact analytical expected number of total tosses required (counting every toss up to and including the T that finishes the first HT) as a float.

def calculate_expected_flips() -> float:

Examples

Example 1

Input:  calculate_expected_flips()
Output: 4.0

A trial finishes in 2 tosses on HT (probability 1/4), in 3 tosses on HHT or THT (combined probability 2/8), in 4 tosses on HHHT, THHT, or TTHT (combined probability 3/16), and in general on toss k with probability (k - 1) / 2^k for every k >= 2. Summing k * (k - 1) / 2^k over k >= 2 evaluates to 4.0.

Example 2

Input:  calculate_expected_flips() / 2.0
Output: 2.0

Waiting for the initial H takes 1 / 0.5 = 2.0 tosses on average, and once at least one H has landed, any additional H still leaves the sequence ending in H, so waiting for the closing T takes another 1 / 0.5 = 2.0 tosses on average (2.0 + 2.0 = 4.0, giving 4.0 / 2.0 = 2.0).

Constraints

  • Each toss is independent with P(H) = 0.5 and P(T) = 0.5.
  • Return the exact closed-form float expectation rather than a randomized simulation estimate.

Step-by-step walkthrough

  1. Restate the problem with concrete coin-flip runs

    We flip a fair coin (P(Heads) = 0.5, P(Tails) = 0.5) over and over until we see Heads immediately followed by Tails (HT). We count every flip from the beginning through both flips of that final HT, and we want the expected number of flips (the long-run average across infinitely many games), returned as a float.

    Let's look at a few sample games so the stopping rule is crystal clear:

    H T          -> stops on toss 2  (total = 2 tosses)
    H H T, T H T -> stops on toss 3  (total = 3 tosses)
    T T H T      -> stops on toss 4  (total = 4 tosses)
    H H H T      -> stops on toss 4  (total = 4 tosses: tosses 3 and 4 form HT!)
    T H H T      -> stops on toss 4  (total = 4 tosses)
    

    Look closely at H H H T: flipping two Hs in a row did not force us to start over from scratch — the latest H was still ready and waiting for the very next T!

  2. Model the game with three tiny memory states

    Trying to sum n * P(stop on flip n) across n = 2, 3, 4, ... means wrestling with an infinite series. Instead, ask: at any moment before stopping, how much of our past history actually affects how many flips remain?

    Only one piece of information matters: whether the flip we just saw was H! That gives us three states: - State S (Start / no active H): Either we have not flipped yet, or our last flip was T (so we have 0 characters of HT matched). - State H (Last flip was H): We have matched the H of HT; one T right now wins the game! - State Done (HT completed): Game over (0 flips remaining).

              T (0.5)                 H (0.5)
              +----+                  +----+
              |    v                  |    v
            [ State S ] ---H (0.5)--> [ State H ] ---T (0.5)--> [ Done ]
             (0 matched)              (H matched)               (0 left)
    

    Notice the self-loop H -> H on Heads: if you are in State H and flip another H, your sequence now ends in HH — its final letter is still H, so you stay right in State H!

  3. Set up and solve the expected-value equations from zero

    Let: - E_S = expected number of remaining flips starting from State S. - E_H = expected number of remaining flips starting from State H.

    Using first-step analysis (every step costs 1 flip right now, plus the probability-weighted average of remaining flips from whichever state we land in next):

    1. From State H, we flip once (+1):
      • With probability 0.5, we get T, landing in Done (0 flips left).
      • With probability 0.5, we get H, staying in State H (E_H flips left).
    E_H = 1 + 0.5 * 0 + 0.5 * E_H
    E_H - 0.5 * E_H = 1
    0.5 * E_H = 1
    E_H = 2
    
    1. From State S, we flip once (+1):
      • With probability 0.5, we get H, moving to State H (E_H flips left).
      • With probability 0.5, we get T, staying in State S (E_S flips left).
    E_S = 1 + 0.5 * E_H + 0.5 * E_S
    E_S - 0.5 * E_S = 1 + 0.5 * E_H
    0.5 * E_S = 1 + 0.5 * 2 = 2
    E_S = 4
    

    Since the game begins in State S, the expected number of flips is 4.0.

  4. Sanity check: two independent geometric waits in a row

    We can verify 4.0 in ten seconds using an even simpler picture! Every game that ends at the first HT splits cleanly into two non-overlapping phases:

    T  T  ...  T  H  |  H  H  ...  H  T
    \______________/    \______________/
      Phase 1: wait       Phase 2: wait
      for first H         for next T
    
    1. Phase 1: Flip until the very first H appears. For a coin with probability p = 0.5, the average wait for a success is 1 / p = 1 / 0.5 = 2 flips.
    2. Phase 2: Once you have that H, every extra H keeps you ending in H, and the very first T finishes HT! Waiting for that T takes another 1 / 0.5 = 2 flips on average.

    Adding the two waits gives 2 + 2 = 4 flips! (Notice why HH takes longer — 6 flips instead of 4: if you are waiting for the second H and flip T, that T destroys your first H and sends you all the way back to Phase 1!)

  5. Translate the general algebra into Python

    Instead of hard-coding return 4.0, writing out the solved formulas in terms of p_heads and p_tails documents our state-machine derivation clearly and even works for any biased coin: - E_H = 1 + p_heads * E_H rearranges to (1 - p_heads) * E_H = 1, which is p_tails * E_H = 1, giving expected_from_h = 1.0 / p_tails. - E_S = 1 + p_heads * E_H + p_tails * E_S rearranges to (1 - p_tails) * E_S = 1 + p_heads * E_H, which is p_heads * E_S = 1 + p_heads * E_H, giving expected_from_start = (1.0 + p_heads * expected_from_h) / p_heads.

  6. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    def calculate_expected_flips() -> float:
        # Fair coin probabilities for a single independent flip.
        p_heads = 0.5
        p_tails = 1.0 - p_heads
    
        # State H (most recent flip was Heads, so one Tails finishes HT):
        # We spend 1 flip now. With probability p_tails we get Tails (0 flips left);
        # with probability p_heads we get Heads and STAY in State H (still ending in H!).
        # Solving E_H = 1 + p_heads * E_H + p_tails * 0  =>  (1 - p_heads) * E_H = 1  =>  E_H = 1 / p_tails
        expected_from_h = 1.0 / p_tails
    
        # State S (start, or last flip was Tails with no HT yet):
        # We spend 1 flip now. With probability p_heads we move to State H;
        # with probability p_tails we get Tails and stay in State S.
        # Solving E_S = 1 + p_heads * E_H + p_tails * E_S  =>  (1 - p_tails) * E_S = 1 + p_heads * E_H
        expected_from_start = (1.0 + p_heads * expected_from_h) / p_heads
    
        return expected_from_start
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Think of HT as a two-step combination lock where Step 1 is flipping Heads and Step 2 is flipping Tails. At the start (and after any Tails before Heads), you are at Step 0. As soon as you flip Heads, you advance to Step 1 — and here is the crucial twist: if your next flip is another Heads, you do not drop back to Step 0! Your sequence ends in HH, so the most recent flip is still Heads, keeping you perched at Step 1 until Tails finally lands. Tracking only the small summary of past flips that matters for the future models the coin flips as a Markov chain (a state diagram where future probabilities depend only on your current state, not the full path taken to get there).

Why do quick guesses often go wrong? Many candidates say "two flips have probability 1/4 of being HT, so the expected wait is 1 / (1/4) = 4." That formula only gets 4 by luck here: consecutive two-flip windows overlap, and the exact same formula falsely predicts 4 for HH, whose true expected wait is 6! Meanwhile, summing n * P(stop on flip n) over n = 2, 3, 4, ... works in principle, but requires summing an infinite series instead of solving two tiny equations.

Let's walk through the state equations using first-step analysis (writing the expected flips from a state as 1 for the flip we are about to make, plus the weighted average of expected remaining flips from each next state):

States: S (0 matched),  H (last flip was Heads),  Done (HT completed, 0 left)

From H: flip once (+1) -> 50% Tails (Done: 0 left), 50% Heads (stay in H: E_H left)
        E_H = 1 + 0.5 * 0 + 0.5 * E_H   ==>   0.5 * E_H = 1          ==>   E_H = 2.0

From S: flip once (+1) -> 50% Heads (go to H: E_H left), 50% Tails (stay in S: E_S left)
        E_S = 1 + 0.5 * E_H + 0.5 * E_S ==>   0.5 * E_S = 1 + 1.0    ==>   E_S = 4.0

Complexity

  • Time: O(1). We evaluate two closed-form arithmetic formulas derived from the 2-state linear system, performing a fixed number of floating-point operations.
  • Space: O(1). We store only four scalar floats (p_heads, p_tails, expected_from_h, and expected_from_start).

Edge cases

  • Minimum possible flip count is 2: You cannot form a 2-character pattern in 0 or 1 flips; HT on the very first two flips happens with probability 0.25, balanced out by longer runs like T T T H H T (6 flips) so the average lands at 4.0.
  • Long streaks of Heads (H H H H T): Extra Heads keep the process in State H rather than resetting to State S; resetting on HH would compute the wrong constant.
  • Exact floating-point representation: Because 0.5, 1.0, 2.0, and 4.0 are exact powers of 2 in binary IEEE-754 floating point, (1.0 + 0.5 * 2.0) / 0.5 evaluates to 4.0 with zero rounding error.
  • Biased coin (0 < p < 1): Our equations E_H = 1 / (1 - p) and E_S = 1 / p + 1 / (1 - p) hold for any Heads probability p; if p = 0 or p = 1, HT can never appear and the expected wait diverges to infinity.

Common mistakes

  • Confusing HT (4 flips) with HH (6 flips): When waiting for HH, flipping T after your first H wipes out your progress and sends you back to State S (E_H = 1 + 0.5 * 0 + 0.5 * E_S), raising the answer to 6. For HT, flipping H after H preserves your progress (E_H = 1 + 0.5 * E_H + 0.5 * 0).
  • Forgetting the + 1 for the current flip: Writing E_H = 0.5 * E_H omits the flip you just spent to leave State H, collapsing the equations to 0.
  • Claiming E[flips] = 1 / P(pattern) for overlapping patterns: 1 / (1/4) = 4 measures the average spacing between occurrences in an infinite flip stream, not the first-arrival wait from scratch when a pattern can overlap itself (such as HH or HTH).
  • Returning a random Monte Carlo simulation average: Simulating 10,000 coin games gives something noisy like 3.987 or 4.019, which fails exact deterministic judge checks and misses the analytical insight the interviewer is testing.

Alternative approaches

  • Sum of two geometric random variables: A geometric distribution counts how many independent trials (each succeeding with probability p) are needed until the first success, and its expected value is 1 / p. Waiting for HT is simply waiting for the first H (E[X_1] = 1 / 0.5 = 2 flips) followed immediately by waiting for the first T after that (E[X_2] = 1 / 0.5 = 2 flips); by linearity of expectation (the rule that E[X_1 + X_2] = E[X_1] + E[X_2] always holds), the total expected flips is 2 + 2 = 4.
  • Infinite series summation: Any n-flip game stopping at the first HT looks like a Tails (a >= 0), then b Heads (b >= 1), then a final T, with a + b = n - 1. There are n - 1 choices for (a, b), so P(N = n) = (n - 1) / 2^n for n >= 2, and summing n * (n - 1) / 2^n over n >= 2 yields 4.

Follow-up questions

  • How many tosses are expected on average to observe two consecutive Heads (HH), and why does that differ from HT? For HH, once you reach State H (one H seen), tossing T breaks your streak and sends you all the way back to State S instead of keeping you in State H. Solving E_H = 1 + 0.5 * 0 + 0.5 * E_S together with E_S = 1 + 0.5 * E_H + 0.5 * E_S gives E_S = 6.0 tosses — two tosses longer than HT because failed attempts from State H forfeit prior progress.
  • How does the expected toss count change if the coin is biased with Heads probability p and Tails probability 1 - p? Waiting for the initial H is a geometric wait with mean 1 / p, and waiting for the closing T afterward is a second geometric wait with mean 1 / (1 - p), so E[N] = 1 / p + 1 / (1 - p) = 1 / (p * (1 - p)). Notice this quantity reaches its minimum of 4.0 at p = 0.5, because making either face rarer stretches one wait more than it shortens the other.
  • In a single continuous stream of fair coin tosses, is HT strictly more likely to appear before HH? Surprisingly, no — each wins with probability 0.5! Neither pattern can complete during any opening run of Ts; as soon as the very first H lands, the single next toss settles the race immediately: H finishes HH (50%) and T finishes HT (50%). HH only has a larger expected toss count (6 vs 4) because whenever HH loses that decisive toss (seeing T), HT stops right away whereas HH must restart from zero.

Follow-up questions

Similar questions

More Yahoo interview questions

All 8 Yahoo questions →