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 pattern is empty after stripping (""), 0 flips are needed—return 0.0.
  • If any character other than 'H' or 'T' (case-insensitive) is present, raise ValueError.

Examples

Example 1

  • Input: pattern = "HHT"
  • Output: 8.0
  • Explanation: Reaching "HH" takes 6 flips on average (2 flips 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 just 2 more flips on average (6 + 2 = 8.0).

Example 2

  • Input: pattern = "HTHT"
  • Output: 20.0
  • Explanation: "HTHT" overlaps with itself at length 2 (its prefix "HT" matches its suffix "HT"). Expected cumulative flip counts to first match prefixes "H", "HT", "HTH", and "HTHT" progress as 2 -> 4 -> 10 -> 20.0.

Constraints

  • 0 <= len(pattern.strip()) <= 50
  • Every character in pattern.strip().upper() must be 'H' or 'T' (otherwise raise ValueError).
  • Coin flips are mutually independent with P(H) = P(T) = 0.5.

Step-by-step walkthrough

  1. 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 target pattern such 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 completes pattern.

  2. Why equal-length patterns do not share the same expected wait

    Any isolated block of n fair flips matches a fixed length-n string with probability (1/2)^n (1/8 for length 3, 1/16 for length 4). It is tempting to conclude from 1 / p that every length-3 target takes 8 flips and every length-4 target takes 16 flips 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 to 0 matched characters (14 flips on average vs. 8 for "HHT").
    • Chasing "HTHT" (Example 2): At "HTH", flipping 'H' gives "HTHH", which still ends with "H" (1 matched character saved rather than 0), yielding 20 flips rather than 16.
  3. 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 pattern currently match the trailing flips of our log.

    Define state k (0 <= k <= n, with n = len(pattern)) as the length of the longest prefix (pattern[:k]) that equals a suffix of the flips seen so far (stopping once state n is reached). Because future transitions depend solely on state k and 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 state 2!

  4. Solve `"HHT"` by hand with first-step equations

    Let E[k] be the expected remaining flips needed to hit state 3 starting from state k, so E[3] = 0 and our goal is E[0]. Taking one flip from state k < 3 costs 1 flip 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 = 8
    
  5. Turn the general method into a one-pass recurrence

    Rather than running O(n³) Gaussian elimination on n equations, exploit the chain's one-step-forward property: a single coin flip can raise our state k by at most +1. Consequently, every path from state 0 to state k + 1 must pass through state 1, state 2, ..., state j, ..., and state k along the way.

    Define first_hit[k] as the expected flips to travel from state 0 to state k for the first time, so first_hit[0] = 0 and the final answer is first_hit[n].

    • Because every run 0 -> (k + 1) visits any j <= k en route and the Markov chain is memoryless after hitting j, linearity of expectation gives first_hit[k + 1] = first_hit[j] + E[flips from j to k + 1], or E[flips from j to k + 1] = first_hit[k + 1] - first_hit[j].
    • From state k, flipping 1 coin either hits pattern[k] (probability 1/2, reaching k + 1 with 0 extra flips) or hits the opposite face (probability 1/2, dropping to fallback <= k, from which first_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 (k and fallback <= k) in exact integer arithmetic!

  6. Compute the fallback state after a wrong flip

    At state matched_len, the recent flips end with pattern[:matched_len]. Appending toss forms candidate_tail = pattern[:matched_len] + toss. Testing suffix lengths from len(candidate_tail) down to 1 finds the longest prefix of pattern that matches a suffix of candidate_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 0
    
  7. Trace Examples 1 and 2 (`"HHT"` and `"HTHT"`)

    Step k from 0 to n - 1 using first_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 = 20
    

    Look at k = 2 in "HHT": fallback = 2 subtracts first_hit[2] = 6, turning 2*6 + 2 = 14 down into 8!

  8. 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 to fallback = 0, 0, 2: first_hit advances 0 -> 2 -> 6 -> (2*6 + 2 - 6 = 8).
  • On Example 2 ("HTHT"), wrong flips drop to fallback = 0, 1, 0, 1: first_hit advances 0 -> 2 -> 4 -> 10 -> (2*10 + 2 - 2 = 20).

Complexity

  • Time: O(n³) as written for n = len(pattern). The outer loop runs n steps, next_state checks up to n suffix lengths, and each slice check compares up to n characters. For short interview patterns (n <= 50), this finishes in microseconds; if n were huge, precomputing fallback transitions via the Knuth-Morris-Pratt (KMP) failure table (an array recording the longest proper prefix of each pattern[:k] that is also its suffix) lowers total time to O(n).
  • Space: O(n), holding n + 1 integers in first_hit and temporary slices of length at most n.

Edge cases

  • Empty pattern (""): Satisfied before any flip occurs, returning 0.0.
  • Single-flip patterns ("H", "T"): Succeed on each flip with probability 1/2, returning 2.0.
  • Pure runs ("TTT", "HHHH"): Every wrong flip resets to fallback = 0, maximizing expected wait for length n at 2 + 4 + ... + 2^n = 2^(n + 1) - 2 (14.0 for n = 3, 30.0 for n = 4).
  • Self-non-overlapping patterns ("HHT", "HTT", "THH", "TTH"): No proper prefix equals a proper suffix of the whole pattern, giving 2^n (8.0 for n = 3).
  • Label swap (H <-> T) or reversal symmetry: Swapping 'H' with 'T' ("HHT" <-> "TTH") or reversing pattern ("HHT" <-> "THH") preserves all prefix-suffix self-overlaps and leaves the expected flip count unchanged on a fair coin.
  • Long patterns (n >= 53): first_hit computes exact arbitrary-precision Python int values before converting to float at the end.

Common mistakes

  • Claiming 2^n for every length-n string: 2^n is 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 0 on every mismatch: Misses partial fallbacks like "HHH" -> "HH" in "HHT" or "HTHH" -> "H" in "HTHT".
  • Forgetting the +1 flip cost or miscounting pattern length: Either dropping the 1 + ... term in the step equation or counting flips prior to the start of pattern instead of up to its completion.
  • Stopping at Monte Carlo simulation without an exact proof: Averaging 100,000 random runs gives ~8.01 and ~19.97, useful as a sanity check, whereas interviewers look for the exact Markov derivation.

Alternative approaches

  • Gaussian elimination on all n Markov equations (O(n³)): Solve E[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²) or O(n) with KMP): A fair-betting (martingale, a zero-expected-gain wagering process) argument proves E[flips] = sum of 2^k across every k (1 <= k <= n) with pattern[:k] == pattern[-k:]. For "HHT" only k = 3 matches (2^3 = 8); for "HTHT" both k = 2 ("HT") and k = 4 ("HTHT") match (2^2 + 2^4 = 4 + 16 = 20); for "TTT" all k = 1, 2, 3 match (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_state fallbacks remain identical; only branch probabilities change. Letting q be the chance of flipping pattern[k] (p if 'H', else 1 - p), first_hit[k + 1] - first_hit[k] = 1 + (1 - q) * (first_hit[k + 1] - first_hit[fallback]) solves to first_hit[k + 1] = (first_hit[k] + 1 - (1 - q) * first_hit[fallback]) / q (matching Conway's generalized sum sum of 1 / P(pattern[:k]) over matching prefix-suffix lengths k).

    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" (probability 1/8), because any 'H' appearing earlier forces every subsequent run toward "TTT" to hit "HTT" first—giving "HTT" a 7/8 (87.5%) win rate! For arbitrary equal-length patterns A and B, either solve hitting probabilities on their combined prefix Markov chain or apply Conway's cross-overlap formula: letting (X : Y) sum 2^k over 1 <= k <= n where X[-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,000 independent runs keeping only a sliding window of the latest len(pattern) flips until it matches pattern, and check that the empirical average lies within 3 standard errors (3 * sample_std / sqrt(trials)) of expected_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

Similar questions

More Bnp interview questions

All 4 Bnp questions →