Coin-Flip Waiting Times and Conditional Probability

Easy · Statistics & Math · Data Scientist · Technical Screen

Problem Statement

Given parameters for an independent coin-tossing process where each toss lands heads with probability coin_probability, along with a list of event-probability triples conditional_cases, compute and return a single flat list of floating-point results containing, in order:

  1. Expected waiting tosses: The expected number of tosses needed to accumulate required_heads heads in total (the heads do not need to land on consecutive tosses).
  2. Fixed-count head probability: The probability of observing exact count exact_heads heads across total_flips independent tosses of the coin (returning 0.0 if exact_heads < 0 or exact_heads > total_flips).
  3. Conditional probabilities: For every [p_a, p_b, p_a_and_b] triple in conditional_cases—giving P(A), P(B), and the joint probability P(A and B) of two events A and B—append the conditional probability P(A | B) in the same order as conditional_cases.
def calculate_probability_answers(
    coin_probability: float,
    required_heads: int,
    total_flips: int,
    exact_heads: int,
    conditional_cases: List[List[float]],
) -> List[float]:

Examples

Example 1

coin_probability = 0.5
required_heads = 3
total_flips = 4
exact_heads = 3
conditional_cases = [[0.4, 0.5, 0.2], [0.6, 0.25, 0.1]]
# Output: [6.0, 0.25, 0.4, 0.4]

Walk-through:

  • Each head of a fair coin (p = 0.5) takes 1 / 0.5 = 2.0 tosses on average, so collecting 3 total heads takes 3 / 0.5 = 6.0 tosses.
  • Across 4 fair tosses, C(4, 3) = 4 sequences (HHHT, HHTH, HTHH, THHH) contain 3 heads, each with probability 0.5^4 = 0.0625, giving 4 * 0.0625 = 0.25.
  • For [0.4, 0.5, 0.2], P(A | B) = 0.2 / 0.5 = 0.4.
  • For [0.6, 0.25, 0.1], P(A | B) = 0.1 / 0.25 = 0.4.

Example 2

coin_probability = 0.2
required_heads = 2
total_flips = 2
exact_heads = 1
conditional_cases = [[0.5, 0.8, 0.2]]
# Output: [10.0, 0.32, 0.25]

Walk-through:

  • Collecting 2 total heads when p = 0.2 takes 2 / 0.2 = 10.0 tosses on average.
  • Exactly 1 head in 2 tosses (HT or TH) has probability 2 * 0.2 * 0.8 = 0.32.
  • For [0.5, 0.8, 0.2], P(A | B) = 0.2 / 0.8 = 0.25.

Constraints

  • 0.0 < coin_probability <= 1.0
  • 1 <= required_heads <= 10^6
  • 0 <= total_flips <= 1,000
  • -1,000 <= exact_heads <= 1,000
  • 0 <= len(conditional_cases) <= 10^4
  • Each triple [p_a, p_b, p_a_and_b] satisfies 0.0 <= p_a <= 1.0, 0.0 < p_b <= 1.0, and 0.0 <= p_a_and_b <= min(p_a, p_b)
  • Floating-point values within 10^-6 relative or absolute tolerance are accepted

Step-by-step walkthrough

  1. Map the three probability tasks to the function parameters

    This problem bundles three core probability calculations into one parameterized Python function:

    • coin_probability (p): probability that a single toss lands heads (0 < p <= 1).
    • required_heads (r): toss repeatedly until you have collected r heads in total (they do not need to be consecutive). Compute the expected number of tosses.
    • total_flips (n) and exact_heads (k): toss the coin n times and compute the probability of seeing exact count k heads.
    • conditional_cases: a list of [P(A), P(B), P(A and B)] triples (with P(B) > 0). For each triple, compute the conditional probability P(A | B).

    We return all results in one flat list: [expected_flips, exact_k_prob, P(A | B) for case 1, P(A | B) for case 2, ...].

  2. Part 1: Expected tosses until r total heads

    Start with the simpler building block: how many tosses E does it take on average to see just 1 head?

    You always spend 1 toss right away:

    • With probability p, that first toss is a head and you stop (0 extra tosses needed).
    • With probability 1 - p, that first toss is a tail. Because coin tosses have no memory, you are right back where you started, still needing E more tosses on average!

    Writing that sentence as an equation solves E in two lines of algebra:

    E = 1 + p * 0 + (1 - p) * E
    E - (1 - p) * E = 1
    p * E = 1   -->   E = 1 / p
    

    For a fair coin (p = 0.5), 1 head takes 1 / 0.5 = 2 tosses on average. Now slice a run until r total heads right after each head arrives:

    Example toss history for r = 3 heads:   T   H  |  T   T   H  |  H
                                            \___/     \_______/     \_/
                                            Wait 1      Wait 2     Wait 3
                                          (mean 1/p)  (mean 1/p) (mean 1/p)
    

    Because heads do not have to be consecutive, a tail during Wait 2 never erases the head you already banked in Wait 1! Each segment is a fresh, independent single-head wait with average 1 / p, so adding r segments gives r / p (3 / 0.5 = 6.0 tosses for three heads of a fair coin).

    def expected_flips_until_heads(p: float, required_heads: int) -> float:
        """Return expected flips until `required_heads` total heads (not necessarily consecutive)."""
        # Waiting for 1 head is a geometric wait with mean 1 / p; by linearity of expectation,
        # waiting for `required_heads` independent heads adds `required_heads` waits of 1 / p.
        return required_heads / p
    
  3. Part 2: Probability of exact k heads in n tosses

    Suppose we toss a coin n = 4 times and want k = 3 heads, as in Example 1. Look at the matching sequences out of the 2^4 = 16 outcomes:

    Matching outcomes (3 heads, 1 tail):   HHHT,  HHTH,  HTHH,  THHH   --> C(4, 3) = 4 ways
    Each specific 4-toss sequence prob:    p^3 * (1 - p)^1 = (0.5)^3 * (0.5)^1 = 0.0625
    Total probability:                     4 * 0.0625 = 0.25
    

    Why isn't the answer just p^k * (1 - p)^(n - k)? Because that expression is the probability of one specific ordering (such as HHHT alone)! There are C(n, k) distinct ways to choose which k of the n toss positions receive the heads, and each of those C(n, k) mutually exclusive sequences has probability p^k * (1 - p)^(n - k):

    P(exactly k heads in n tosses) = C(n, k) * p^k * (1 - p)^(n - k)
    

    In code, we guard exact_heads < 0 or exact_heads > total_flips upfront and return 0.0: besides being impossible in real life, math.comb(n, k) raises ValueError when k < 0, and when p = 1.0 with k > n, (1.0 - p) ** (n - k) evaluates 0.0 ** (negative integer), raising ZeroDivisionError.

    def binomial_probability(total_flips: int, exact_heads: int, p: float) -> float:
        """Return P(exactly `exact_heads` heads in `total_flips` independent flips)."""
        # Guard impossible counts upfront: math.comb rejects negative k, and p == 1.0 with
        # exact_heads > total_flips would raise ZeroDivisionError on 0.0 ** (negative power).
        if exact_heads < 0 or exact_heads > total_flips:
            return 0.0
    
        ways_to_place_heads = math.comb(total_flips, exact_heads)
        single_sequence_prob = (p ** exact_heads) * ((1.0 - p) ** (total_flips - exact_heads))
        return ways_to_place_heads * single_sequence_prob
    
  4. Part 3: Conditional probability and checking independence

    Asking for P(A | B) means: "We already know event B happened—among outcomes inside B, what fraction also belong to A?"

    Original sample space (total area = 1.0):
    +-----------------------------------------+
    |                  +-------------------+  |
    |   A only         |  A ∩ B  |  B only |  |
    |                  +-------------------+  |
    |                             \_______/   |
    |                         Event B = new 100%
    +-----------------------------------------+
    
    Fraction of B that is also in A:  P(A | B) = P(A and B) / P(B)
    

    Dividing the overlap P(A and B) by P(B) rescales B to become our new 100% universe. Look at the two triples in Example 1:

    • Case 1 (P(A) = 0.4, P(B) = 0.5, P(A and B) = 0.2): P(A | B) = 0.2 / 0.5 = 0.4. Notice P(A | B) == P(A) (0.4 == 0.4) because P(A) * P(B) = 0.2 = P(A and B)—events A and B are statistically independent.
    • Case 2 (P(A) = 0.6, P(B) = 0.25, P(A and B) = 0.1): P(A | B) = 0.1 / 0.25 = 0.4. Here P(A | B) = 0.4 != P(A) = 0.6, showing A is less likely once B occurs—the two events are dependent!

    Notice that P(A) is never used inside the division p_a_and_b / p_b; comparing P(A | B) against P(A) simply tells an analyst whether B carries information about A.

    def conditional_probability(p_a_and_b: float, p_b: float) -> float:
        """Return P(A | B) = P(A and B) / P(B), rescaling B to be the new 100% sample space."""
        return p_a_and_b / p_b
    
  5. Assemble the combined output list

    Now calculate_probability_answers calls our three helpers in order: the expected toss count first, the binomial probability second, and then one P(A | B) entry for each [p_a, p_b, p_a_and_b] triple in conditional_cases.

    def calculate_probability_answers(coin_probability: float, required_heads: int, total_flips: int, exact_heads: int, conditional_cases: List[List[float]]) -> List[float]:
        # answers: flat output list [expected_flips, binomial_prob, P(A|B) for each case...]
        expected_flips = expected_flips_until_heads(coin_probability, required_heads)
        exact_k_prob = binomial_probability(total_flips, exact_heads, coin_probability)
        answers: List[float] = [expected_flips, exact_k_prob]
    
        # Each case in conditional_cases has shape [P(A), P(B), P(A and B)].
        for case in conditional_cases:
            # P(A) is unused in P(A | B); it only reveals whether P(A | B) == P(A) (independence).
            p_a, p_b, p_a_and_b = case
            answers.append(conditional_probability(p_a_and_b, p_b))
    
        return answers
    
  6. Trace Example 1 end to end

    Let's trace calculate_probability_answers(0.5, 3, 4, 3, [[0.4, 0.5, 0.2], [0.6, 0.25, 0.1]]):

    1. expected_flips_until_heads(0.5, 3):
       required_heads / p = 3 / 0.5 = 6.0
    
    2. binomial_probability(4, 3, 0.5):
       C(4, 3) * (0.5^3) * (0.5^1) = 4 * 0.125 * 0.5 = 0.25
    
    3. conditional_cases[0] = [0.4, 0.5, 0.2]:
       p_a_and_b / p_b = 0.2 / 0.5 = 0.4
    
    4. conditional_cases[1] = [0.6, 0.25, 0.1]:
       p_a_and_b / p_b = 0.1 / 0.25 = 0.4
    
    Returned list: [6.0, 0.25, 0.4, 0.4]
    
  7. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    import math
    
    
    def expected_flips_until_heads(p: float, required_heads: int) -> float:
        """Return expected flips until `required_heads` total heads (not necessarily consecutive)."""
        # Waiting for 1 head is a geometric wait with mean 1 / p; by linearity of expectation,
        # waiting for `required_heads` independent heads adds `required_heads` waits of 1 / p.
        return required_heads / p
    
    
    def binomial_probability(total_flips: int, exact_heads: int, p: float) -> float:
        """Return P(exactly `exact_heads` heads in `total_flips` independent flips)."""
        # Guard impossible counts upfront: math.comb rejects negative k, and p == 1.0 with
        # exact_heads > total_flips would raise ZeroDivisionError on 0.0 ** (negative power).
        if exact_heads < 0 or exact_heads > total_flips:
            return 0.0
    
        ways_to_place_heads = math.comb(total_flips, exact_heads)
        single_sequence_prob = (p ** exact_heads) * ((1.0 - p) ** (total_flips - exact_heads))
        return ways_to_place_heads * single_sequence_prob
    
    
    def conditional_probability(p_a_and_b: float, p_b: float) -> float:
        """Return P(A | B) = P(A and B) / P(B), rescaling B to be the new 100% sample space."""
        return p_a_and_b / p_b
    
    
    def calculate_probability_answers(coin_probability: float, required_heads: int, total_flips: int, exact_heads: int, conditional_cases: List[List[float]]) -> List[float]:
        # answers: flat output list [expected_flips, binomial_prob, P(A|B) for each case...]
        expected_flips = expected_flips_until_heads(coin_probability, required_heads)
        exact_k_prob = binomial_probability(total_flips, exact_heads, coin_probability)
        answers: List[float] = [expected_flips, exact_k_prob]
    
        # Each case in conditional_cases has shape [P(A), P(B), P(A and B)].
        for case in conditional_cases:
            # P(A) is unused in P(A | B); it only reveals whether P(A | B) == P(A) (independence).
            p_a, p_b, p_a_and_b = case
            answers.append(conditional_probability(p_a_and_b, p_b))
    
        return answers
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Think of the three probability rules here through everyday mental models:

  1. Collecting stamps for r total heads: If 1 in every 2 coin tosses lands heads (p = 0.5), you expect to spend 1 / p = 2 tosses per head—that single-success waiting count follows a geometric distribution (the number of independent trials needed until the first success). Because the problem asks for r heads not necessarily in a row, banking each head locks in your progress permanently; by linearity of expectation (the rule that the expected value, or long-run average, of a sum of random quantities always equals the sum of their individual averages), waiting for r total heads—a negative binomial distribution—adds r waits of 1 / p to give r / p.
  2. Counting winning seating charts for k heads in n tosses: Each specific sequence of k heads and n - k tails (such as HHHT) has chance p^k * (1 - p)^(n - k), and there are C(n, k) ways to choose which k toss slots get the heads, giving the binomial distribution probability mass function (PMF) (a formula assigning the exact probability to each discrete outcome).
  3. Zooming the camera into B for conditional probability: Conditional probability P(A | B) asks what share of B's world also falls inside A, so we divide their overlap P(A and B) by P(B).

Why do rushed intuition shortcuts go wrong here? Candidates frequently confuse "collect r heads total" (r / p, where tails never erase banked heads) with "r consecutive heads in a row" (where any tail resets your streak back to zero), forget to multiply by C(n, k) and report 0.5^4 = 0.0625 for just one ordering instead of all 4 orderings (0.25), or divide by P(A) instead of P(B) when computing P(A | B).

Here is a step-by-step trace of Example 1 (p = 0.5, r = 3, n = 4, k = 3, plus two event pairs):

1. Expected tosses for 3 heads total:
   Wait 1 (2.0) + Wait 2 (2.0) + Wait 3 (2.0) = 3 / 0.5 = 6.0

2. Exactly 3 heads in 4 fair tosses:
   Winning sequences = {HHHT, HHTH, HTHH, THHH} -> C(4, 3) = 4 ways
   Each sequence has prob (0.5)^3 * (0.5)^1 = 0.0625 -> 4 * 0.0625 = 0.25

3. Conditional cases:
   [P(A)=0.4, P(B)=0.5,  P(A and B)=0.2] -> P(A | B) = 0.2 / 0.5  = 0.4  (independent: equals P(A))
   [P(A)=0.6, P(B)=0.25, P(A and B)=0.1] -> P(A | B) = 0.1 / 0.25 = 0.4  (dependent: differs from P(A))

Complexity

Let m = len(conditional_cases) and n = total_flips.

  • Time: O(m) for the conditional cases (plus O(1) arithmetic for small n). expected_flips_until_heads is a single division, conditional_probability performs one division for each of the m cases, and binomial_probability performs one math.comb(n, k) call and two exponentiations (constant time for typical n, scaling with n if n grows into large big-integer factorials).
  • Space: O(m). Aside from a handful of scalar variables, memory goes solely to the returned answers list of length m + 2.

Edge cases

  • Impossible head counts (exact_heads < 0 or exact_heads > total_flips): Returns 0.0 immediately, avoiding ValueError in math.comb for negative k and ZeroDivisionError from 0.0 ** (n - k) when p = 1.0 and k > n.
  • Zero heads or all heads (k = 0 or k = n): C(n, 0) = C(n, n) = 1, cleanly returning (1 - p)^n or p^n.
  • Zero tosses (n = 0, k = 0): Python evaluates 0.0 ** 0 as 1.0, so 0 tosses yield 0 heads with probability 1.0.
  • Guaranteed heads (p = 1.0): r heads take r / 1.0 = r tosses, P(X = n) = 1.0, and P(X = k) = 0.0 for k < n.
  • Subset and disjoint conditional cases: When B lies completely inside A (P(A and B) == P(B)), P(A | B) = 1.0; when A and B are disjoint events (mutually exclusive events that can never happen together, so P(A and B) == 0), P(A | B) = 0.0.
  • Empty conditional_cases ([]): Returns just [expected_flips, exact_k_prob].
  • Large n float overflow (n >= 1030): math.comb(1030, 515) exceeds IEEE-754 double precision (~1.8e308), raising OverflowError when multiplied by a float. For huge n and 0 < p < 1, compute in log space using log-gamma (math.lgamma(x) computes ln((x - 1)!) without overflowing): math.exp(math.lgamma(n + 1) - math.lgamma(k + 1) - math.lgamma(n - k + 1) + k * math.log(p) + (n - k) * math.log(1 - p)).

Common mistakes

  • Confusing cumulative heads with a consecutive streak: Two heads in total at p = 0.5 take 2 / 0.5 = 4 tosses on average because HTH finishes on toss 3, whereas two consecutive heads HH take 6 tosses because a tail after one head resets your streak.
  • Multiplying instead of dividing (r * p or r / (1 - p)): Sanity-check with a rare coin like p = 0.01—a rarer head must require more tosses (100 per head, not 0.01), confirming p belongs in the denominator.
  • Forgetting C(n, k) in the binomial probability: Reporting p^k * (1 - p)^(n - k) counts only one fixed ordering of heads and tails instead of all C(n, k) orderings.
  • Dividing by P(A) instead of P(B): P(A and B) / P(A) computes P(B | A), the reverse conditional probability; always divide by the probability of the given condition after the | bar.
  • Confusing "independent" with "disjoint": Statistical independence means P(A and B) = P(A) * P(B) (one event gives zero information about the other); disjoint events with positive probabilities have P(A and B) = 0 != P(A) * P(B), meaning they are maximally dependent (if B happened, A definitely did not).

Follow-up questions

  • How does the expected flip count change if the required two heads must appear back to back (HH)? Track your active streak length (0 heads vs 1 trailing head) and let E0 and E1 be the expected remaining tosses from each state. From streak 0, one toss moves you to streak 1 with probability p or leaves you at 0 with probability 1 - p (E0 = 1 + p * E1 + (1 - p) * E0); from streak 1, a head finishes immediately while a tail resets you back to 0 (E1 = 1 + (1 - p) * E0). Substituting E1 into E0 yields E0 = (1 + p) / p^2 = 1/p + 1/p^2, which is 2 + 4 = 6 tosses for a fair coin instead of 2 / 0.5 = 4 tosses for two non-consecutive heads.
  • What are the variance and standard deviation of the total flips needed to collect r non-consecutive heads? A single geometric wait until one head has variance (1 - p) / p^2. Because the r segments between consecutive heads are mutually independent, their variances sum directly: Var(T) = r * (1 - p) / p^2, and the standard deviation is sqrt(Var(T)). For Example 1 (p = 0.5, r = 3), Var(T) = 3 * 0.5 / 0.25 = 6.0, giving a standard deviation of sqrt(6) ≈ 2.45 tosses around the mean of 6.0.
  • How would you verify these closed-form probability answers with a Monte Carlo check in Python? Simulate N = 100,000 independent trials with random.random() < p and compare the empirical average against the analytical answer using the standard error (SD / sqrt(N), the typical random fluctuation of a sample average over N trials). For p = 0.5, r = 3 (SD ≈ 2.45), the standard error over 100,000 runs is 2.45 / sqrt(100,000) ≈ 0.0077, so a valid simulation mean will almost always fall within ±0.03 (~4 standard errors) of 6.0, immediately exposing formula errors.

Follow-up questions

Similar questions

More Experian interview questions

All 5 Experian questions →