Fair-Coin Streaks and Bayesian Bias Updating

Hard · Statistics & Math · Data Scientist · Online Assessment

Problem Statement

Implement solve_coin_question(question: int) -> object to compute exact analytical answers to three independent coin-flipping probability and inference sub-problems selected by question:

def solve_coin_question(question: int) -> object:
  1. Competing three-flip sequences (question == 1): An unbiased coin (P(H) = P(T) = 0.5) is flipped independently over and over until either the contiguous pattern "HHH" or the contiguous pattern "THH" appears. Return as a float the exact probability that "HHH" occurs before "THH".

  2. Expected maximum head streak (question == 2): An unbiased coin is flipped 15 independent times. Let L be the length of the longest contiguous streak of "H" outcomes across those 15 flips (L = 0 when all 15 flips land "T"). Return E[L] as an exact float.

  3. Posterior bias distribution (question == 3): A coin lands heads with unknown probability theta in [0, 1], whose prior density on [0, 1] is proportional to theta^3. Suppose 4 independent flips of this coin all land heads. Return a dictionary describing the exact normalized posterior distribution of theta with four keys:

    • "family": "Beta"
    • "alpha": integer first shape parameter (int)
    • "beta": integer second shape parameter (int)
    • "density": normalized density expression string "<constant> * theta^<alpha-1> * (1 - theta)^<beta-1> for 0 <= theta <= 1", omitting any factor whose exponent is 0 and omitting ^1 when an exponent is 1.

For any question value other than 1, 2, or 3, raise ValueError.

Examples

The miniature companion cases below illustrate the exact rules and return formats without revealing the numerical answers for question = 1, 2, 3:

Example 1

Companion race ("HH" before "TH" on a fair coin):
  Opening flips "HH" (probability 1/4) -> "HH" completes immediately.
  Opening flip  "T..." (probability 3/4 across non-"HH" starts) -> once any "T" has landed,
  the very first "H" afterward completes "TH" before "HH" can ever form.
  Exact probability = 0.25  (returned as float by solve_coin_question(1) for "HHH" vs "THH")

Whenever one pattern's suffix overlaps the other pattern's prefix, the race can be far from 0.5 even though isolated windows have equal probability.

Example 2

Companion streak expectation (3 fair coin flips, 8 equally likely outcomes):
  L = 0: {TTT}                   -> 1 outcome
  L = 1: {HTT, THT, TTH, HTH}    -> 4 outcomes
  L = 2: {HHT, THH}              -> 2 outcomes
  L = 3: {HHH}                   -> 1 outcome
  Exact expectation = (0*1 + 1*4 + 2*2 + 3*1) / 8 = 1.375
  (solve_coin_question(2) returns the corresponding float for 15 fair flips)

Summing exact rational probabilities avoids Monte Carlo sampling noise.

Example 3

Companion Bayesian update (prior density proportional to theta on [0, 1], 2 flips both heads):
  Prior theta^1 = theta^(2 - 1) * (1 - theta)^(1 - 1)  -> Beta(alpha=2, beta=1)
  Likelihood of 2 heads = theta^2                      -> posterior proportional to theta^3
  Normalized posterior dictionary:
  {
    "family": "Beta",
    "alpha": 4,
    "beta": 1,
    "density": "4 * theta^3 for 0 <= theta <= 1"
  }
  (solve_coin_question(3) returns this dictionary schema for prior theta^3 and 4 heads;
   solve_coin_question(0) raises ValueError)

Because beta - 1 == 0, (1 - theta)^0 equals 1 and is omitted from "density", while the constant 4 ensures the density integrates to 1 over [0, 1].

Constraints

  • Valid selector values are question in {1, 2, 3}; all other integer inputs must raise ValueError.
  • Floating-point results for question == 1 and question == 2 are checked within 1e-6 relative/absolute tolerance, so random Monte Carlo trials without exact arithmetic are too noisy.
  • Standard library only (fractions, math, etc.).

Step-by-step walkthrough

  1. Understand the three sub-problems and exactness requirements

    solve_coin_question(question) answers three probability and statistics puzzles depending on question:

    1. question == 1: Repeatedly flip a fair coin. Return P(HHH appears before THH) as a float.
    2. question == 2: Flip a fair coin 15 times. Return E[longest consecutive run of heads] as a float.
    3. question == 3: Given a coin bias theta on [0, 1] with prior density proportional to theta^3 and 4 flips that all land heads, return the posterior distribution as a dictionary: {"family": "Beta", "alpha": 8, "beta": 1, "density": "8 * theta^7 for 0 <= theta <= 1"}.

    Notice why random Monte Carlo simulation is not sufficient here: even 1,000,000 simulated games leave random sampling noise around 0.001, whereas the judge checks floating-point answers to 1e-6. By solving each part with exact Fraction arithmetic and converting to float only on the final line, we eliminate simulation noise completely.

  2. Question 1 logic: why THH traps every late HHH

    At first glance, HHH and THH each have probability (1/2)^3 = 1/8 on any isolated block of 3 tosses, tempting people to guess 1/2. That guess fails because the end of THH (HH) is the start of HHH.

    Suppose HHH appears for the very first time at tosses (k, k + 1, k + 2):

    Case A: k = 1 (first three tosses are H, H, H)
      Tosses:   H   H   H
      --> No 'T' has ever appeared, so THH is impossible. HHH wins!
          Probability = (1/2) * (1/2) * (1/2) = 1/8 = 0.125
    
    Case B: k > 1 (HHH finishes after toss 3, so toss k - 1 exists)
      Toss index:   k-1   k   k+1   k+2
      Must be:       T    H    H     H
                     \_________/
                  THH already finished at toss k+1 (one toss BEFORE HHH)!
    

    Why must toss k - 1 be T in Case B? Because if toss k - 1 were H, then tosses (k - 1, k, k + 1) would already be HHH, contradicting that toss k + 2 was the first time HHH finished! Therefore, the only way HHH ever beats THH is on the very first three flips, giving 1/8 = 0.125.

  3. Question 1 code: state-machine probability propagation

    In an interview, give the 4-line proof above first. In code, we can verify it with a reusable state machine that works on any pair of patterns (first vs second):

    • Only the last max(len(first), len(second)) - 1 flips can contribute to an unfinished pattern (2 flips for length-3 patterns).
    • We maintain active_states, mapping each undecided recent suffix to its exact Fraction probability, starting from {"": Fraction(1)}.
    • Each flip splits every active state's probability in half (+'H' and +'T'), adding mass that completes first into first_wins, discarding mass that completes second, and merging the remaining branches by their new suffix.
    Toss 0:  { "": 1 }
    Toss 1:  { "H": 1/2, "T": 1/2 }
    Toss 2:  { "HH": 1/4, "HT": 1/4, "TH": 1/4, "TT": 1/4 }
    Toss 3:  "HH"+H -> "HHH" (first_wins += 1/8!)
             "TH"+H -> "THH" (second wins 1/8, discarded)
             Remaining active_states: { "HT": 2/8, "TH": 2/8, "TT": 2/8 }
             (Notice "HH" is gone forever: reaching "HH" from "TH" completes "THH" first!)
    
    def pattern_race(first: str, second: str, tolerance: float = 1e-15) -> float:
        """Return P(`first` appears before `second`) when tossing a fair coin."""
        # Only the last (max_pattern_len - 1) tosses can form part of an unfinished pattern.
        suffix_len = max(len(first), len(second)) - 1
    
        # active_states: maps recent toss suffix (str) -> exact probability (Fraction),
        # e.g. {'HT': Fraction(1, 4), 'TH': Fraction(1, 4), 'TT': Fraction(1, 4)}
        active_states: Dict[str, Fraction] = {"": Fraction(1)}
        first_wins = Fraction(0)
    
        # Advance one fair toss at a time until remaining undecided probability <= tolerance.
        while sum(active_states.values()) > tolerance:
            next_states: Dict[str, Fraction] = {}
            for history_suffix, state_prob in active_states.items():
                branch_prob = state_prob / 2
                for coin_face in ("H", "T"):
                    extended = history_suffix + coin_face
                    if extended.endswith(first):
                        first_wins += branch_prob
                    elif extended.endswith(second):
                        # `second` appeared first on this branch, so discard its mass.
                        continue
                    else:
                        # Guard suffix_len == 0 because extended[-0:] would keep the whole string.
                        if suffix_len == 0:
                            next_state = ""
                        else:
                            next_state = extended[-suffix_len:]
                        next_states[next_state] = next_states.get(next_state, Fraction(0)) + branch_prob
            active_states = next_states
    
        return float(first_wins)
    
  4. Question 2 idea: the tail-sum formula and bounded-run DP

    Enumerating all 2^n coin sequences takes O(n * 2^n) time — fast enough for n = 15 (32,768 sequences), but impossible for n = 100. Instead, we combine two clean ideas that run in O(n^3) integer operations:

    1. The tail-sum formula for expected value. Let L be the longest run of heads (0 <= L <= n). Normally E[L] = 1*P(L = 1) + 2*P(L = 2) + 3*P(L = 3) + .... Look what happens if we write k copies of P(L = k) vertically and sum by rows instead of columns:
    Row k = 1:  P(L=1) + P(L=2) + P(L=3) + ... + P(L=n)   =  P(L >= 1)
    Row k = 2:           P(L=2) + P(L=3) + ... + P(L=n)   =  P(L >= 2)
    Row k = 3:                    P(L=3) + ... + P(L=n)   =  P(L >= 3)
    ...
    ------------------------------------------------------------------
    Col sums:   1*P(L=1) + 2*P(L=2) + 3*P(L=3) + ...      =  E[L]
    

    So E[L] = sum_{k=1..n} P(L >= k). And since L >= k is the exact opposite of L <= k - 1, we only need a helper that counts sequences whose longest head streak never exceeds max_allowed_run = k - 1!

    1. Dynamic programming by current trailing streak. Build a valid sequence flip by flip. At any point, the only thing we need to know to enforce max_run <= max_allowed_run on future flips is r, how many consecutive 'H's sit at the very end right now (0 <= r <= max_allowed_run):
      • Appending 'T' resets any streak back to 0, so next_ways[0] = sum(ways_by_trailing_heads).
      • Appending 'H' moves streak r to r + 1 for 0 <= r < max_allowed_run, while sequences already at r == max_allowed_run are dropped so they never reach max_allowed_run + 1!
  5. Question 2 code and 4-toss hand trace

    Let's write both functions and verify them on n = 4 (2^4 = 16 sequences) before running n = 15:

    def count_sequences_with_max_run_at_most(num_tosses: int, max_allowed_run: int) -> int:
        """Count length-`num_tosses` H/T sequences whose longest H-streak is <= `max_allowed_run`."""
        # ways_by_trailing_heads[r]: valid prefixes built so far ending in r consecutive 'H's,
        # for 0 <= r <= max_allowed_run.
        ways_by_trailing_heads = [0] * (max_allowed_run + 1)
        ways_by_trailing_heads[0] = 1
    
        for _ in range(num_tosses):
            next_ways = [0] * (max_allowed_run + 1)
            # Flipping 'T' resets any trailing 'H' streak back to 0.
            next_ways[0] = sum(ways_by_trailing_heads)
            # Flipping 'H' extends r heads to r + 1 heads; r == max_allowed_run is dropped
            # because extending it would create (max_allowed_run + 1) consecutive heads.
            for streak_len in range(max_allowed_run):
                next_ways[streak_len + 1] = ways_by_trailing_heads[streak_len]
            ways_by_trailing_heads = next_ways
    
        return sum(ways_by_trailing_heads)
    
    
    def expected_longest_run(num_tosses: int) -> float:
        """Compute E[longest consecutive run of heads] in `num_tosses` fair coin flips."""
        total_sequences = 2 ** num_tosses
        expected = Fraction(0)
    
        # Tail-sum identity for whole numbers: E[L] = sum_{k=1..n} P(L >= k),
        # where P(L >= k) = 1 - P(L <= k - 1).
        for k in range(1, num_tosses + 1):
            at_most_k_minus_1 = count_sequences_with_max_run_at_most(num_tosses, k - 1)
            at_least_k = total_sequences - at_most_k_minus_1
            expected += Fraction(at_least_k, total_sequences)
    
        return float(expected)
    

    Check n = 3 (Example 2) by hand and compare with n = 15:

    Hand check for n = 3 (8 total sequences, matching Example 2):
      k = 1: max_run <= 0 is {TTT} (1 seq)           -> P(L >= 1) = (8 - 1)/8 = 7/8
      k = 2: max_run <= 1 has no 'HH' (5 seqs)       -> P(L >= 2) = (8 - 5)/8 = 3/8
      k = 3: max_run <= 2 drops only HHH (7 seqs)    -> P(L >= 3) = (8 - 7)/8 = 1/8
      Sum E[L] = (7 + 3 + 1) / 8 = 11 / 8 = 1.375
    
    For n = 15 (32,768 total sequences):
      Numerators of P(L >= k) for k = 1..15:
      32767 + 31171 + 22159 + 12199 + 5984 + 2798 + 1279 + 576 + 256 + 112 + 48 + 20 + 8 + 3 + 1
      = 109381
      E[L] = 109381 / 32768 = 3.338043212890625
    
  6. Question 3 idea: Bayes' rule and conjugate Beta priors

    Let theta (between 0 and 1) be the coin's unknown probability of landing heads.

    • Prior belief: Before flipping, our belief about theta has density proportional to theta^3. Compare that with the standard Beta distribution Beta(alpha, beta), whose density on [0, 1] is proportional to: theta^(alpha - 1) * (1 - theta)^(beta - 1) Matching exponents gives alpha - 1 = 3 (so alpha = 4) and beta - 1 = 0 (so beta = 1). Thus the prior is Beta(4, 1)!
    • Likelihood of the data: Since flips are independent given theta, the probability of seeing 4 heads in 4 tosses is theta * theta * theta * theta = theta^4.
    • Bayes' rule (posterior proportional to prior * likelihood):
    Unnormalized posterior:
      p(theta | HHHH)  proportional to  theta^3  *  theta^4  =  theta^7
                                       (prior)    (4 heads)
    
    Match exponents with theta^(alpha - 1) * (1 - theta)^(beta - 1):
      alpha - 1 = 7  -->  alpha = 8
      beta  - 1 = 0  -->  beta  = 1     (this is Beta(8, 1)!)
    
    Normalize so total area on [0, 1] equals 1:
      integral from 0 to 1 of theta^7 d(theta) = [theta^8 / 8] from 0 to 1 = 1/8
      Divide by 1/8  -->  p(theta | HHHH) = 8 * theta^7 for 0 <= theta <= 1
    

    Because a Beta prior multiplied by coin-flip likelihood always stays a Beta distribution (alpha gains #heads, beta gains #tails), the Beta family is called the conjugate prior for coin flips.

  7. Question 3 code: exact Beta posterior dictionary

    For any whole-number parameters alpha >= 1 and beta >= 1, calculus tells us the normalizing constant 1 / B(alpha, beta) equals (alpha + beta - 1)! / ((alpha - 1)! * (beta - 1)!). Let's verify on alpha = 8, beta = 1: (8 + 1 - 1)! / (7! * 0!) = 8! / 7! = 8.

    We format the density string carefully to match the required output schema ("8 * theta^7 for 0 <= theta <= 1"), omitting any power-zero factor like (1 - theta)^0:

    def beta_posterior(prior_alpha: int, prior_beta: int, heads: int, tails: int) -> Dict[str, Any]:
        """Update a Beta(prior_alpha, prior_beta) prior after seeing `heads` H and `tails` T."""
        # Conjugate Beta-Binomial update: heads add to alpha, tails add to beta.
        alpha = prior_alpha + heads
        beta = prior_beta + tails
    
        # For positive integers, 1 / B(alpha, beta) = (alpha + beta - 1)! / ((alpha - 1)! (beta - 1)!).
        normalizer = factorial(alpha + beta - 1) // (factorial(alpha - 1) * factorial(beta - 1))
    
        factors = [str(normalizer)]
        if alpha - 1 == 1:
            factors.append("theta")
        elif alpha - 1 > 1:
            factors.append(f"theta^{alpha - 1}")
    
        if beta - 1 == 1:
            factors.append("(1 - theta)")
        elif beta - 1 > 1:
            factors.append(f"(1 - theta)^{beta - 1}")
    
        density = " * ".join(factors) + " for 0 <= theta <= 1"
        return {
            "family": "Beta",
            "alpha": alpha,
            "beta": beta,
            "density": density,
        }
    
  8. Complete solution

    Putting all three parts together behind solve_coin_question:

    from typing import Any, Dict, List, Optional, Set, Tuple
    from fractions import Fraction
    from math import factorial
    
    
    def pattern_race(first: str, second: str, tolerance: float = 1e-15) -> float:
        """Return P(`first` appears before `second`) when tossing a fair coin."""
        # Only the last (max_pattern_len - 1) tosses can form part of an unfinished pattern.
        suffix_len = max(len(first), len(second)) - 1
    
        # active_states: maps recent toss suffix (str) -> exact probability (Fraction),
        # e.g. {'HT': Fraction(1, 4), 'TH': Fraction(1, 4), 'TT': Fraction(1, 4)}
        active_states: Dict[str, Fraction] = {"": Fraction(1)}
        first_wins = Fraction(0)
    
        # Advance one fair toss at a time until remaining undecided probability <= tolerance.
        while sum(active_states.values()) > tolerance:
            next_states: Dict[str, Fraction] = {}
            for history_suffix, state_prob in active_states.items():
                branch_prob = state_prob / 2
                for coin_face in ("H", "T"):
                    extended = history_suffix + coin_face
                    if extended.endswith(first):
                        first_wins += branch_prob
                    elif extended.endswith(second):
                        # `second` appeared first on this branch, so discard its mass.
                        continue
                    else:
                        # Guard suffix_len == 0 because extended[-0:] would keep the whole string.
                        if suffix_len == 0:
                            next_state = ""
                        else:
                            next_state = extended[-suffix_len:]
                        next_states[next_state] = next_states.get(next_state, Fraction(0)) + branch_prob
            active_states = next_states
    
        return float(first_wins)
    
    
    def count_sequences_with_max_run_at_most(num_tosses: int, max_allowed_run: int) -> int:
        """Count length-`num_tosses` H/T sequences whose longest H-streak is <= `max_allowed_run`."""
        # ways_by_trailing_heads[r]: valid prefixes built so far ending in r consecutive 'H's,
        # for 0 <= r <= max_allowed_run.
        ways_by_trailing_heads = [0] * (max_allowed_run + 1)
        ways_by_trailing_heads[0] = 1
    
        for _ in range(num_tosses):
            next_ways = [0] * (max_allowed_run + 1)
            # Flipping 'T' resets any trailing 'H' streak back to 0.
            next_ways[0] = sum(ways_by_trailing_heads)
            # Flipping 'H' extends r heads to r + 1 heads; r == max_allowed_run is dropped
            # because extending it would create (max_allowed_run + 1) consecutive heads.
            for streak_len in range(max_allowed_run):
                next_ways[streak_len + 1] = ways_by_trailing_heads[streak_len]
            ways_by_trailing_heads = next_ways
    
        return sum(ways_by_trailing_heads)
    
    
    def expected_longest_run(num_tosses: int) -> float:
        """Compute E[longest consecutive run of heads] in `num_tosses` fair coin flips."""
        total_sequences = 2 ** num_tosses
        expected = Fraction(0)
    
        # Tail-sum identity for whole numbers: E[L] = sum_{k=1..n} P(L >= k),
        # where P(L >= k) = 1 - P(L <= k - 1).
        for k in range(1, num_tosses + 1):
            at_most_k_minus_1 = count_sequences_with_max_run_at_most(num_tosses, k - 1)
            at_least_k = total_sequences - at_most_k_minus_1
            expected += Fraction(at_least_k, total_sequences)
    
        return float(expected)
    
    
    def beta_posterior(prior_alpha: int, prior_beta: int, heads: int, tails: int) -> Dict[str, Any]:
        """Update a Beta(prior_alpha, prior_beta) prior after seeing `heads` H and `tails` T."""
        # Conjugate Beta-Binomial update: heads add to alpha, tails add to beta.
        alpha = prior_alpha + heads
        beta = prior_beta + tails
    
        # For positive integers, 1 / B(alpha, beta) = (alpha + beta - 1)! / ((alpha - 1)! (beta - 1)!).
        normalizer = factorial(alpha + beta - 1) // (factorial(alpha - 1) * factorial(beta - 1))
    
        factors = [str(normalizer)]
        if alpha - 1 == 1:
            factors.append("theta")
        elif alpha - 1 > 1:
            factors.append(f"theta^{alpha - 1}")
    
        if beta - 1 == 1:
            factors.append("(1 - theta)")
        elif beta - 1 > 1:
            factors.append(f"(1 - theta)^{beta - 1}")
    
        density = " * ".join(factors) + " for 0 <= theta <= 1"
        return {
            "family": "Beta",
            "alpha": alpha,
            "beta": beta,
            "density": density,
        }
    
    
    def solve_coin_question(question: int) -> object:
        if question == 1:
            return pattern_race("HHH", "THH")
        if question == 2:
            return expected_longest_run(15)
        if question == 3:
            # Prior p(theta) proportional to theta^3 = theta^(4 - 1) * (1 - theta)^(1 - 1)
            # is Beta(alpha=4, beta=1); observing 4 heads adds 4 to alpha and 0 to beta.
            return beta_posterior(prior_alpha=4, prior_beta=1, heads=4, tails=0)
        raise ValueError(f"unknown question number: {question}")
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Each of the three questions rewards looking at the structure of transitions rather than brute-forcing individual flip histories:

  1. Pattern race (HHH before THH): Imagine THH as a mandatory tollbooth sitting right before HHH's highway exit. The only way to reach HHH without driving through THH first is to start at the exit on your very first three flips (H, H, H, probability 1/8). The moment even one T lands, any future streak of heads must spell T -> TH -> THH one flip before it could ever spell HHH! In code, we verify this with a Markov state machine (a model that remembers only the last few flips needed to detect a pattern, rather than the entire flip history).
  2. Expected longest head streak in 15 flips: Instead of scanning all 2^15 flip strings, we use dynamic programming (solving a counting problem step by step by grouping sequences that share the same current state — here, the number of consecutive 'H's at the end) alongside the tail-sum formula (computing the average of a non-negative whole number L by adding P(L >= 1) + P(L >= 2) + ... + P(L >= n)).
  3. Bayesian coin inference: Think of a Beta distribution Beta(alpha, beta) (a continuous probability curve on [0, 1] proportional to theta^(alpha - 1) * (1 - theta)^(beta - 1)) as a running tally of alpha virtual heads and beta virtual tails. Because it is a conjugate prior (a prior family whose updated posterior distribution after seeing data stays in the exact same family), Bayes' rule (updating prior density by multiplying by the probability of the observed data and re-normalizing to area 1) simply adds the 4 observed heads to alpha!

Why do naive approaches fail? Guessing 0.5 for Question 1 ignores overlap: HHH and THH occur equally often over the long run, yet THH wins 7/8 of head-to-head races! Estimating Questions 1 and 2 via random.choice leaves sampling error around 10^-3 even after a million trials — far too coarse for a 10^-6 judge tolerance. And in Question 3, misreading theta^3 as alpha = 3 instead of alpha - 1 = 3 (alpha = 4) shifts the entire posterior off by one.

Here is how all three calculations work on our companion traces and target inputs:

Q1 (Companion HH vs TH -> 1/4; target HHH vs THH -> 1/8):
  First 3 flips == HHH (prob 1/8) -> HHH wins immediately.
  First 3 flips != HHH (prob 7/8) -> at least one 'T' exists before any 'HHH',
                                     so 'THH' always finishes first -> P = 0.125.

Q2 (Longest head run on n = 3 flips from Example 2, 8 sequences):
  P(L >= 1) = 7/8  (all except TTT)
  P(L >= 2) = 3/8  (HHT, THH, HHH)
  P(L >= 3) = 1/8  (HHH)
  E[L] = 7/8 + 3/8 + 1/8 = 11/8 = 1.375  (for n = 15: 109381 / 32768 = 3.338043212890625)

Q3 (Companion theta^1 + 2 heads -> Beta(4,1); target theta^3 + 4 heads -> Beta(8,1)):
  Prior: theta^3 = Beta(4, 1)  -->  +4 heads, +0 tails  -->  Posterior: Beta(8, 1)
  Normalize theta^7 on [0, 1]: integral is 1/8, so density = 8 * theta^7.

Complexity

  • Question 1 (pattern_race): Let m be the maximum pattern length (m = 3 here). At most 2^(m - 1) suffixes (4 suffixes for m = 3) can be active at once, so each simulated flip inspects O(2^(m - 1)) states and checks string suffixes in O(m) time. Reaching 1e-15 undecided probability takes O(log(1 / tolerance)) flips (165 iterations for HHH vs THH), using O(2^(m - 1)) space. (Using the closed-form proof (1/2)^3 = 1/8 takes O(1) time and O(1) space.)
  • Question 2 (expected_longest_run): For n flips (n = 15), count_sequences_with_max_run_at_most(n, limit) runs n iterations over an array of length limit + 1, costing O(n * limit) arithmetic operations. Calling it for limit = 0, 1, ..., n - 1 totals O(n^3) integer operations (only a few thousand steps for n = 15, versus O(n * 2^n) for full enumeration) and O(n) space for the ways_by_trailing_heads list.
  • Question 3 (beta_posterior): O(alpha + beta) arithmetic steps to compute three small integer factorials (8! at largest here) and O(1) space.

Edge cases

  • Question 1, non-trivial pattern pairs: HHH vs THH is decided by toss 3 because THH ends with HH, but other pairs such as HTH vs HHT (P = 1/3) can run arbitrarily long; pattern_race handles both.
  • Question 1, short history and length-1 patterns: On toss 1 ("H"), extended[-2:] safely returns "H"; when suffix_len == 0 (length-1 patterns), we explicitly return "" because Python treats -0 as 0 (extended[0:] would keep the entire string instead of clearing it).
  • Question 2, boundary k = 1 (max_allowed_run = 0): Only the all-tails sequence TT...T (1 sequence) has zero heads, so P(L >= 1) = (2^n - 1) / 2^n.
  • Question 2, exact binary denominator: Because every sequence of 15 fair flips has probability 1 / 32768, E[L] = 109381 / 32768 is an exact binary fraction representable with zero rounding loss in IEEE-754 float.
  • Question 3, beta == 1 (beta - 1 == 0): Since (1 - theta)^0 = 1, that factor is omitted from the formatted density string ("8 * theta^7 for 0 <= theta <= 1"). Similarly, an exponent of 1 formats cleanly without ^1.
  • Question 3, unnormalized prior input: The statement writes p(theta) proportional to theta^3 without its prior normalizing constant 4. Because Bayes' rule re-normalizes at the end, multiplying or omitting constants in the prior never changes the posterior.

Common mistakes

  • Answering 0.5 for Question 1 ("Penney's game" trap): Even though E[flips until HHH] = 14 and HHH and THH each have probability 1/8 at any fixed 3-flip window, head-to-head races depend on how one pattern's suffix overlaps the other's prefix.
  • Using Monte Carlo random trials for Questions 1 or 2: Standard error shrinks only as 1 / sqrt(trials), requiring roughly 10^12 simulated games to guarantee 1e-6 accuracy.
  • Off-by-one errors in the tail-sum loop: Starting k at 0 adds P(L >= 0) = 1 extra unit to the expectation; using count_sequences_with_max_run_at_most(n, k) instead of (n, k - 1) computes 1 - P(L <= k) = P(L > k) and misses P(L >= 1).
  • Reading theta^3 as Beta(3, 1) instead of Beta(4, 1): In Beta(alpha, beta), the exponent on theta is alpha - 1, not alpha. Starting from alpha = 3 yields Beta(7, 1) instead of Beta(8, 1).
  • Forgetting the normalizing constant 8 in Question 3: theta^7 integrates to 1/8 on [0, 1], so a valid probability density function must multiply by 8 to integrate to 1.

Follow-up questions

  • How can you compute the head-to-head winning probability for any two fair-coin patterns directly without iterating toss by toss? Use Conway's leading-number algorithm! For any two patterns A and B (neither inside the other), define the overlap score A : B by checking each length k = 1..min(len(A), len(B)): whenever the last k letters of A equal the first k letters of B, add 2^(k - 1). Then the exact odds that B appears before A are (A : A - A : B) to (B : B - B : A). For A = HHH and B = THH, we get A : A = 1 + 2 + 4 = 7, A : B = 0, B : B = 4, and B : A = 1 + 2 = 3, giving odds (7 - 0) to (4 - 3) = 7 : 1 against HHH, or P(HHH first) = 1/8.
  • As the number of fair coin flips n grows large, how does the expected longest consecutive run of heads scale? It grows logarithmically, roughly as log2(n) (more precisely, oscillating tightly around log2(n / 2) + gamma / ln(2) + 0.5, which is roughly log2(n) - 0.6). Doubling the number of coin flips increases the expected longest streak by about 1 head (3.34 at n = 15, 4.29 at n = 30, 5.26 at n = 60), which is why seeing a streak of 7 or 8 heads in 200 fair flips is completely normal rather than evidence of a rigged coin!
  • Under the Beta(8, 1) posterior from part 3, what is the predictive probability that flip 5 lands heads, and how would observing tails update the distribution? The posterior predictive probability of heads on the next flip equals the mean of theta under the posterior, which for Beta(alpha, beta) is simply alpha / (alpha + beta) = 8 / (8 + 1) = 8/9 (up from the prior mean 4/5, and smoother than the naive maximum-likelihood estimate 4/4 = 1). If that 5th toss landed tails, beta would increment by 1 to Beta(8, 2) with density 72 * theta^7 * (1 - theta) and new mean 8/10 = 0.8.

Follow-up questions

Similar questions

More Five Rings interview questions

All 1 Five Rings questions →