Expected Flips Until a Target Coin Sequence
Easy · Software Engineering Fundamentals · Data Scientist · Technical Screen
Problem Statement
An unbiased coin (P(H) = 0.5, P(T) = 0.5) is flipped independently one flip at a time, appending 'H' (heads) or 'T' (tails) to a running log. Flipping stops at the exact moment a target sequence pattern appears for the first time as a contiguous substring of that log.
Write expected_tosses_for_pattern(pattern: str) -> float to return the exact expected total number of flips performed up to and including the flip that completes pattern.
def expected_tosses_for_pattern(pattern: str) -> float:
...
Input Normalization & Edge Rules
- Strip leading/trailing whitespace and treat letters case-insensitively (
"hht"and"HHT"represent the same target). - If
patternis empty after stripping (""),0flips are needed—return0.0. - If any character other than
'H'or'T'(case-insensitive) is present, raiseValueError.
Examples
Example 1
- Input:
pattern = "HHT" - Output:
8.0 - Explanation: Reaching
"HH"takes6flips on average (2flips to see'H', and from"H"flipping'T'resets to""). Once at"HH", flipping'T'completes"HHT"right away while flipping'H'yields"HHH", whose last two flips are still"HH"—so'H'stays at two matched characters rather than resetting, adding just2more flips on average (6 + 2 = 8.0).
Example 2
- Input:
pattern = "HTHT" - Output:
20.0 - Explanation:
"HTHT"overlaps with itself at length2(its prefix"HT"matches its suffix"HT"). Expected cumulative flip counts to first match prefixes"H","HT","HTH", and"HTHT"progress as2 -> 4 -> 10 -> 20.0.
Constraints
0 <= len(pattern.strip()) <= 50- Every character in
pattern.strip().upper()must be'H'or'T'(otherwise raiseValueError). - Coin flips are mutually independent with
P(H) = P(T) = 0.5.
Step-by-step walkthrough
Understand the stopping rule
We flip a fair coin (
P(H) = 1/2,P(T) = 1/2, independent flips) repeatedly and record the growing string of'H'and'T'outcomes until a targetpatternsuch as"HHT"or"HTHT"occurs as a contiguous run for the very first time. We stop right away and count every flip made so far, including the final flip that completespattern.Why equal-length patterns do not share the same expected wait
Any isolated block of
nfair flips matches a fixed length-nstring with probability(1/2)^n(1/8for length3,1/16for length4). It is tempting to conclude from1 / pthat every length-3 target takes8flips and every length-4 target takes16flips on average.That shortcut breaks because sliding windows overlap, so different patterns salvage very different amounts of progress after a wrong flip:
- Chasing
"HHT"(Example 1): Suppose your first two flips are"HH"and the third flip is'H'instead of'T', giving"HHH". Even though'H'missed'T', the latest two flips are still"HH"— you stay one flip away from"HHT"instead of starting over! - Chasing
"TTT": Suppose your first two flips are"TT"and the third flip is'H', giving"TTH". No non-empty ending of"TTH"begins"TTT", so all progress is wiped out back to0matched characters (14flips on average vs.8for"HHT"). - Chasing
"HTHT"(Example 2): At"HTH", flipping'H'gives"HTHH", which still ends with"H"(1matched character saved rather than0), yielding20flips rather than16.
- Chasing
Model progress as a Markov state machine
What is the smallest piece of history we ever need to remember? Only how many leading characters of
patterncurrently match the trailing flips of our log.Define state
k(0 <= k <= n, withn = len(pattern)) as the length of the longest prefix (pattern[:k]) that equals a suffix of the flips seen so far (stopping once statenis reached). Because future transitions depend solely on statekand not on older flips, these states form a Markov chain.Compare the state diagrams for
"HHT"and"TTT":Pattern "HHT" (states: 0="", 1="H", 2="HH", 3="HHT" [DONE]) H H T [0: ""] ----------> [1: "H"] ---------> [2: "HH"] ---------> [3: "HHT"] ^ | | ^ | | +-- T | T ("HT" -> "") +--| H ("HHH" -> "HH") +--------------------+ Pattern "TTT" (states: 0="", 1="T", 2="TT", 3="TTT" [DONE]) T T T [0: ""] ----------> [1: "T"] ---------> [2: "TT"] ---------> [3: "TTT"] ^ | | | | +-- H | H ("TH" -> "") | H ("TTH" -> "") +--------------------+-------------------+Notice state
2 ("HH")in"HHT": an extra'H'loops right back to state2!Solve `"HHT"` by hand with first-step equations
Let
E[k]be the expected remaining flips needed to hit state3starting from statek, soE[3] = 0and our goal isE[0]. Taking one flip from statek < 3costs1flip plus the average of the two equally likely next states:E[k] = 1 + 0.5 * E[state after H] + 0.5 * E[state after T]Solve the three equations for Example 1 (
"HHT"):State 0 (""): E0 = 1 + 0.5 * E1 + 0.5 * E0 -> 0.5 * E0 = 1 + 0.5 * E1 -> E1 = E0 - 2 State 1 ("H"): E1 = 1 + 0.5 * E2 + 0.5 * E0 -> (E0 - 2) = 1 + 0.5 * E2 + 0.5 * E0 -> 0.5 * E0 - 3 = 0.5 * E2 -> E2 = E0 - 6 State 2 ("HH"): E2 = 1 + 0.5 * E2 + 0.5 * 0 (H stays in state 2, T finishes!) -> 0.5 * E2 = 1 -> E2 = 2 Substitute E2 = 2 into E2 = E0 - 6: -> 2 = E0 - 6 -> E0 = 8Turn the general method into a one-pass recurrence
Rather than running
O(n³)Gaussian elimination onnequations, exploit the chain's one-step-forward property: a single coin flip can raise our statekby at most+1. Consequently, every path from state0to statek + 1must pass through state1, state2, ..., statej, ..., and statekalong the way.Define
first_hit[k]as the expected flips to travel from state0to statekfor the first time, sofirst_hit[0] = 0and the final answer isfirst_hit[n].- Because every run
0 -> (k + 1)visits anyj <= ken route and the Markov chain is memoryless after hittingj, linearity of expectation givesfirst_hit[k + 1] = first_hit[j] + E[flips from j to k + 1], orE[flips from j to k + 1] = first_hit[k + 1] - first_hit[j]. - From state
k, flipping1coin either hitspattern[k](probability1/2, reachingk + 1with0extra flips) or hits the opposite face (probability1/2, dropping tofallback <= k, from whichfirst_hit[k + 1] - first_hit[fallback]expected flips remain):
first_hit[k + 1] - first_hit[k] = 1 + 0.5 * 0 + 0.5 * (first_hit[k + 1] - first_hit[fallback]) Multiply both sides by 2: 2 * first_hit[k + 1] - 2 * first_hit[k] = 2 + first_hit[k + 1] - first_hit[fallback] Rearrange for first_hit[k + 1]: first_hit[k + 1] = 2 * first_hit[k] + 2 - first_hit[fallback]Every
first_hit[k + 1]uses only already-computed entries (kandfallback <= k) in exact integer arithmetic!- Because every run
Compute the fallback state after a wrong flip
At state
matched_len, the recent flips end withpattern[:matched_len]. Appendingtossformscandidate_tail = pattern[:matched_len] + toss. Testing suffix lengths fromlen(candidate_tail)down to1finds the longest prefix ofpatternthat matches a suffix ofcandidate_tail:def next_state(pattern: str, matched_len: int, toss: str) -> int: """Return the longest prefix length of `pattern` that is a suffix of pattern[:matched_len] + toss.""" candidate_tail = pattern[:matched_len] + toss for length in range(len(candidate_tail), 0, -1): if candidate_tail[-length:] == pattern[:length]: return length return 0Trace Examples 1 and 2 (`"HHT"` and `"HTHT"`)
Step
kfrom0ton - 1usingfirst_hit[k + 1] = 2 * first_hit[k] + 2 - first_hit[fallback]:Example 1: clean_pattern = "HHT", start with first_hit = [0, ?, ?, ?] k = 0: needed='H', wrong='T', tail="T" -> fallback = 0 -> first_hit[1] = 2*0 + 2 - 0 = 2 k = 1: needed='H', wrong='T', tail="HT" -> fallback = 0 -> first_hit[2] = 2*2 + 2 - 0 = 6 k = 2: needed='T', wrong='H', tail="HHH" -> fallback = 2 -> first_hit[3] = 2*6 + 2 - 6 = 8 Example 2: clean_pattern = "HTHT", start with first_hit = [0, ?, ?, ?, ?] k = 0: needed='H', wrong='T', tail="T" -> fallback = 0 -> first_hit[1] = 2*0 + 2 - 0 = 2 k = 1: needed='T', wrong='H', tail="HH" -> fallback = 1 -> first_hit[2] = 2*2 + 2 - 2 = 4 k = 2: needed='H', wrong='T', tail="HTT" -> fallback = 0 -> first_hit[3] = 2*4 + 2 - 0 = 10 k = 3: needed='T', wrong='H', tail="HTHH" -> fallback = 1 -> first_hit[4] = 2*10 + 2 - 2 = 20Look at
k = 2in"HHT":fallback = 2subtractsfirst_hit[2] = 6, turning2*6 + 2 = 14down into8!Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple def next_state(pattern: str, matched_len: int, toss: str) -> int: """Return the longest prefix length of `pattern` that is a suffix of pattern[:matched_len] + toss.""" # Rebuild the known tail of recent tosses plus the new coin flip, e.g. "H" + "H" = "HH". candidate_tail = pattern[:matched_len] + toss # Check from longest possible overlap down to 1 so the first match we return is maximal. for length in range(len(candidate_tail), 0, -1): if candidate_tail[-length:] == pattern[:length]: return length return 0 def expected_tosses_for_pattern(pattern: str) -> float: """Return the expected number of fair-coin tosses until `pattern` first appears consecutively.""" # Phase 1: Normalize whitespace/case and verify every character is 'H' or 'T'. clean_pattern = pattern.strip().upper() for ch in clean_pattern: if ch not in ("H", "T"): raise ValueError("pattern may only contain 'H' and 'T'") n = len(clean_pattern) # first_hit[k]: exact integer expected tosses from state 0 ("") to first reach state k # (having matched clean_pattern[:k]); e.g. for "HHT", first_hit = [0, 2, 6, 8]. first_hit: List[int] = [0] * (n + 1) # Phase 2: Advance one matched character at a time using first-step expectation + fallback. for k in range(n): needed_toss = clean_pattern[k] wrong_toss = "T" if needed_toss == "H" else "H" fallback = next_state(clean_pattern, k, wrong_toss) # From state k, we spend 1 toss: # - prob 1/2: we flip `needed_toss` and reach k + 1 immediately (0 extra tosses). # - prob 1/2: we flip `wrong_toss`, drop to `fallback`, and still need # (first_hit[k + 1] - first_hit[fallback]) expected tosses to reach k + 1. # Solving (first_hit[k + 1] - first_hit[k]) = 1 + 0.5 * (first_hit[k + 1] - first_hit[fallback]) # for first_hit[k + 1] yields the exact integer update below: first_hit[k + 1] = 2 * first_hit[k] + 2 - first_hit[fallback] return float(first_hit[n])✅ Submit now — all tests should pass.
Intuition & how it works
Imagine unlocking a combo lock by flipping a fair coin (H or T) on every turn. If your target combo is "TTT" and you flip "TTH", that 'H' wipes out all progress back to 0. Yet if your target combo is "HHT" and you flip "HHH", the third 'H' missed 'T' while still leaving "HH" as the last two flips—keeping 2 matched characters intact! We formalize this with a Markov chain — a step-by-step random process whose future depends only on its current state, never on older history — where state k is the length of the longest prefix (beginning) of pattern matching the suffix (ending) of the flips made so far.
Assuming every length-n pattern takes 2^n flips (8 for length 3, 16 for length 4) fails because adjacent flip windows overlap and are not independent. Assuming every wrong flip resets progress all the way to 0 also fails whenever a mismatch leaves a reusable prefix behind (predicting 14 instead of 8 on "HHT", and 30 instead of 20 on "HTHT").
Let first_hit[k] store the expected flips from state 0 to first reach state k. Because a single flip increases k by at most +1, every journey to k + 1 passes through every j <= k, yielding the exact integer rule first_hit[k + 1] = 2 * first_hit[k] + 2 - first_hit[fallback]:
- On Example 1 (
"HHT"), wrong flips drop tofallback = 0, 0, 2:first_hitadvances0 -> 2 -> 6 -> (2*6 + 2 - 6 = 8). - On Example 2 (
"HTHT"), wrong flips drop tofallback = 0, 1, 0, 1:first_hitadvances0 -> 2 -> 4 -> 10 -> (2*10 + 2 - 2 = 20).
Complexity
- Time:
O(n³)as written forn = len(pattern). The outer loop runsnsteps,next_statechecks up tonsuffix lengths, and each slice check compares up toncharacters. For short interview patterns (n <= 50), this finishes in microseconds; ifnwere huge, precomputing fallback transitions via the Knuth-Morris-Pratt (KMP) failure table (an array recording the longest proper prefix of eachpattern[:k]that is also its suffix) lowers total time toO(n). - Space:
O(n), holdingn + 1integers infirst_hitand temporary slices of length at mostn.
Edge cases
- Empty pattern (
""): Satisfied before any flip occurs, returning0.0. - Single-flip patterns (
"H","T"): Succeed on each flip with probability1/2, returning2.0. - Pure runs (
"TTT","HHHH"): Every wrong flip resets tofallback = 0, maximizing expected wait for lengthnat2 + 4 + ... + 2^n = 2^(n + 1) - 2(14.0forn = 3,30.0forn = 4). - Self-non-overlapping patterns (
"HHT","HTT","THH","TTH"): No proper prefix equals a proper suffix of the whole pattern, giving2^n(8.0forn = 3). - Label swap (
H <-> T) or reversal symmetry: Swapping'H'with'T'("HHT" <-> "TTH") or reversingpattern("HHT" <-> "THH") preserves all prefix-suffix self-overlaps and leaves the expected flip count unchanged on a fair coin. - Long patterns (
n >= 53):first_hitcomputes exact arbitrary-precision Pythonintvalues before converting tofloatat the end.
Common mistakes
- Claiming
2^nfor every length-nstring:2^nis the mean gap between consecutive occurrences in an infinite flip stream, NOT the wait until the first occurrence when occurrences clump via self-overlap (e.g.,"TTTT"packs two overlapping"TTT"matches back-to-back, spacing clumps further apart!). - Resetting to state
0on every mismatch: Misses partial fallbacks like"HHH" -> "HH"in"HHT"or"HTHH" -> "H"in"HTHT". - Forgetting the
+1flip cost or miscounting pattern length: Either dropping the1 + ...term in the step equation or counting flips prior to the start ofpatterninstead of up to its completion. - Stopping at Monte Carlo simulation without an exact proof: Averaging
100,000random runs gives~8.01and~19.97, useful as a sanity check, whereas interviewers look for the exact Markov derivation.
Alternative approaches
- Gaussian elimination on all
nMarkov equations (O(n³)): SolveE[k] = 1 + 0.5 * E[next(k, 'H')] + 0.5 * E[next(k, 'T')](0 <= k < n,E[n] = 0) directly. More verbose for a single pattern, yet extends cleanly to multi-pattern races. - Conway's overlap sum (
O(n²)orO(n)with KMP): A fair-betting (martingale, a zero-expected-gain wagering process) argument provesE[flips] = sum of 2^kacross everyk(1 <= k <= n) withpattern[:k] == pattern[-k:]. For"HHT"onlyk = 3matches (2^3 = 8); for"HTHT"bothk = 2("HT") andk = 4("HTHT") match (2^2 + 2^4 = 4 + 16 = 20); for"TTT"allk = 1, 2, 3match (2 + 4 + 8 = 14).
Follow-up questions
-
How does the recurrence change when the coin is biased with P(H) = p and P(T) = 1 - p? All Markov states and
next_statefallbacks remain identical; only branch probabilities change. Lettingqbe the chance of flippingpattern[k](pif'H', else1 - p),first_hit[k + 1] - first_hit[k] = 1 + (1 - q) * (first_hit[k + 1] - first_hit[fallback])solves tofirst_hit[k + 1] = (first_hit[k] + 1 - (1 - q) * first_hit[fallback]) / q(matching Conway's generalized sumsum of 1 / P(pattern[:k])over matching prefix-suffix lengthsk).python def expected_tosses_biased(pattern: str, p_heads: float) -> float: n = len(pattern) first_hit = [0.0] * (n + 1) for k in range(n): q = p_heads if pattern[k] == "H" else 1.0 - p_heads wrong = "T" if pattern[k] == "H" else "H" fallback = next_state(pattern, k, wrong) first_hit[k + 1] = (first_hit[k] + 1.0 - (1.0 - q) * first_hit[fallback]) / q return first_hit[n] -
In a two-player race between two equal-length patterns (Penney's game), how do you find each player's winning probability? Solo waiting times do not decide head-to-head races! For instance, racing
"TTT"against"HTT","TTT"can win only if the opening three flips are"TTT"(probability1/8), because any'H'appearing earlier forces every subsequent run toward"TTT"to hit"HTT"first—giving"HTT"a7/8(87.5%) win rate! For arbitrary equal-length patternsAandB, either solve hitting probabilities on their combined prefix Markov chain or apply Conway's cross-overlap formula: letting(X : Y)sum2^kover1 <= k <= nwhereX[-k:] == Y[:k],P(B beats A) = ((A:A) - (A:B)) / ((A:A) - (A:B) + (B:B) - (B:A)). -
How would you build a fast Monte Carlo check to verify your exact formula? Simulate
100,000independent runs keeping only a sliding window of the latestlen(pattern)flips until it matchespattern, and check that the empirical average lies within3standard errors (3 * sample_std / sqrt(trials)) ofexpected_tosses_for_pattern(pattern).```python import random
def simulate_expected_tosses(pattern: str, trials: int = 100_000, seed: int = 42) -> float: rng = random.Random(seed) window_len = len(pattern) total_tosses = 0 for _ in range(trials): tail = "" tosses = 0 while tail != pattern: tail = (tail + rng.choice("HT"))[-window_len:] tosses += 1 total_tosses += tosses return total_tosses / trials ```
Follow-up questions
- How does the recurrence change when the coin is biased with P(H) = p and P(T) = 1 - p?
- In a two-player race between two equal-length patterns (Penney's game), how do you find each player's winning probability?
- How would you build a fast Monte Carlo check to verify your exact formula?
Similar questions
- Black-Scholes Option Delta and Hedging
- Blind Coin Partition for Matching Head Counts
- OLS Linear Regression Conditions, Diagnostics, and Remedies
- Dynamic Dynasty Succession Without an Initial Monarch
- DOM Button Click Listener and Event Target
- Catalog Search, Filtering, and Pagination