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.5andP(T) = 0.5. - Return the exact closed-form
floatexpectation rather than a randomized simulation estimate.
Step-by-step walkthrough
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 seeHeadsimmediately followed byTails(HT). We count every flip from the beginning through both flips of that finalHT, and we want the expected number of flips (the long-run average across infinitely many games), returned as afloat.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 twoHs in a row did not force us to start over from scratch — the latestHwas still ready and waiting for the very nextT!Model the game with three tiny memory states
Trying to sum
n * P(stop on flip n)acrossn = 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: - StateS(Start / no activeH): Either we have not flipped yet, or our last flip wasT(so we have0characters ofHTmatched). - StateH(Last flip wasH): We have matched theHofHT; oneTright now wins the game! - StateDone(HTcompleted): Game over (0flips 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 -> HonHeads: if you are inState Hand flip anotherH, your sequence now ends inHH— its final letter is stillH, so you stay right inState H!Set up and solve the expected-value equations from zero
Let: -
E_S= expected number of remaining flips starting fromState S. -E_H= expected number of remaining flips starting fromState H.Using first-step analysis (every step costs
1flip right now, plus the probability-weighted average of remaining flips from whichever state we land in next):- From
State H, we flip once (+1):- With probability
0.5, we getT, landing inDone(0flips left). - With probability
0.5, we getH, staying inState H(E_Hflips left).
- With probability
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- From
State S, we flip once (+1):- With probability
0.5, we getH, moving toState H(E_Hflips left). - With probability
0.5, we getT, staying inState S(E_Sflips left).
- With probability
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 = 4Since the game begins in
State S, the expected number of flips is4.0.- From
Sanity check: two independent geometric waits in a row
We can verify
4.0in ten seconds using an even simpler picture! Every game that ends at the firstHTsplits 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- Phase 1: Flip until the very first
Happears. For a coin with probabilityp = 0.5, the average wait for a success is1 / p = 1 / 0.5 = 2flips. - Phase 2: Once you have that
H, every extraHkeeps you ending inH, and the very firstTfinishesHT! Waiting for thatTtakes another1 / 0.5 = 2flips on average.
Adding the two waits gives
2 + 2 = 4flips! (Notice whyHHtakes longer —6flips instead of4: if you are waiting for the secondHand flipT, thatTdestroys your firstHand sends you all the way back to Phase 1!)- Phase 1: Flip until the very first
Translate the general algebra into Python
Instead of hard-coding
return 4.0, writing out the solved formulas in terms ofp_headsandp_tailsdocuments our state-machine derivation clearly and even works for any biased coin: -E_H = 1 + p_heads * E_Hrearranges to(1 - p_heads) * E_H = 1, which isp_tails * E_H = 1, givingexpected_from_h = 1.0 / p_tails. -E_S = 1 + p_heads * E_H + p_tails * E_Srearranges to(1 - p_tails) * E_S = 1 + p_heads * E_H, which isp_heads * E_S = 1 + p_heads * E_H, givingexpected_from_start = (1.0 + p_heads * expected_from_h) / p_heads.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, andexpected_from_start).
Edge cases
- Minimum possible flip count is
2: You cannot form a 2-character pattern in0or1flips;HTon the very first two flips happens with probability0.25, balanced out by longer runs likeT T T H H T(6flips) so the average lands at4.0. - Long streaks of
Heads(H H H H T): ExtraHeadskeep the process inState Hrather than resetting toState S; resetting onHHwould compute the wrong constant. - Exact floating-point representation: Because
0.5,1.0,2.0, and4.0are exact powers of2in binary IEEE-754 floating point,(1.0 + 0.5 * 2.0) / 0.5evaluates to4.0with zero rounding error. - Biased coin (
0 < p < 1): Our equationsE_H = 1 / (1 - p)andE_S = 1 / p + 1 / (1 - p)hold for any Heads probabilityp; ifp = 0orp = 1,HTcan never appear and the expected wait diverges to infinity.
Common mistakes
- Confusing
HT(4flips) withHH(6flips): When waiting forHH, flippingTafter your firstHwipes out your progress and sends you back toState S(E_H = 1 + 0.5 * 0 + 0.5 * E_S), raising the answer to6. ForHT, flippingHafterHpreserves your progress (E_H = 1 + 0.5 * E_H + 0.5 * 0). - Forgetting the
+ 1for the current flip: WritingE_H = 0.5 * E_Homits the flip you just spent to leaveState H, collapsing the equations to0. - Claiming
E[flips] = 1 / P(pattern)for overlapping patterns:1 / (1/4) = 4measures the average spacing between occurrences in an infinite flip stream, not the first-arrival wait from scratch when a pattern can overlap itself (such asHHorHTH). - Returning a random Monte Carlo simulation average: Simulating
10,000coin games gives something noisy like3.987or4.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 is1 / p. Waiting forHTis simply waiting for the firstH(E[X_1] = 1 / 0.5 = 2flips) followed immediately by waiting for the firstTafter that (E[X_2] = 1 / 0.5 = 2flips); by linearity of expectation (the rule thatE[X_1 + X_2] = E[X_1] + E[X_2]always holds), the total expected flips is2 + 2 = 4. - Infinite series summation: Any
n-flip game stopping at the firstHTlooks likeaTails (a >= 0), thenbHeads (b >= 1), then a finalT, witha + b = n - 1. There aren - 1choices for(a, b), soP(N = n) = (n - 1) / 2^nforn >= 2, and summingn * (n - 1) / 2^novern >= 2yields4.
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 reachState H(oneHseen), tossingTbreaks your streak and sends you all the way back toState Sinstead of keeping you inState H. SolvingE_H = 1 + 0.5 * 0 + 0.5 * E_Stogether withE_S = 1 + 0.5 * E_H + 0.5 * E_SgivesE_S = 6.0tosses — two tosses longer thanHTbecause failed attempts fromState Hforfeit 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
His a geometric wait with mean1 / p, and waiting for the closingTafterward is a second geometric wait with mean1 / (1 - p), soE[N] = 1 / p + 1 / (1 - p) = 1 / (p * (1 - p)). Notice this quantity reaches its minimum of4.0atp = 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 ofTs; as soon as the very firstHlands, the single next toss settles the race immediately:HfinishesHH(50%) andTfinishesHT(50%).HHonly has a larger expected toss count (6vs4) because wheneverHHloses that decisive toss (seeingT),HTstops right away whereasHHmust restart from zero.
Follow-up questions
- How many tosses are expected on average to observe two consecutive Heads (HH), and why does that differ from HT?
- How does the expected toss count change if the coin is biased with Heads probability p and Tails probability 1 - p?
- In a single continuous stream of fair coin tosses, is HT strictly more likely to appear before HH?
Similar questions
- Uniform Sum Check for Relabeled Dice
- Customer Spend and Daily Revenue Metrics
- A/B Test Design for an In-App Recommendation Widget
- Chain Lowercase Words by Overlapping Endpoints
- Model Fit Diagnostics, Skewed Classes, and Missing Features
- Sort Unseen Candidates by Vector Inner Product
More Yahoo interview questions
- Model Fit Diagnostics, Skewed Classes, and Missing Features Easy
- Sort Unseen Candidates by Vector Inner Product Easy
- Customer Spend and Daily Revenue Metrics Medium Pro
- A/B Test Design for an In-App Recommendation Widget Medium Pro
- Chain Lowercase Words by Overlapping Endpoints Medium Pro
- Uniform Sum Check for Relabeled Dice Medium Pro
- Order-Preserving Deduplication and Boundary Word Merging Medium Pro