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:
- Expected waiting tosses: The expected number of tosses needed to accumulate
required_headsheads in total (the heads do not need to land on consecutive tosses). - Fixed-count head probability: The probability of observing exact count
exact_headsheads acrosstotal_flipsindependent tosses of the coin (returning0.0ifexact_heads < 0orexact_heads > total_flips). - Conditional probabilities: For every
[p_a, p_b, p_a_and_b]triple inconditional_cases—givingP(A),P(B), and the joint probabilityP(A and B)of two eventsAandB—append the conditional probabilityP(A | B)in the same order asconditional_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) takes1 / 0.5 = 2.0tosses on average, so collecting3total heads takes3 / 0.5 = 6.0tosses. - Across
4fair tosses,C(4, 3) = 4sequences (HHHT,HHTH,HTHH,THHH) contain3heads, each with probability0.5^4 = 0.0625, giving4 * 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
2total heads whenp = 0.2takes2 / 0.2 = 10.0tosses on average. - Exactly
1head in2tosses (HTorTH) has probability2 * 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.01 <= required_heads <= 10^60 <= total_flips <= 1,000-1,000 <= exact_heads <= 1,0000 <= len(conditional_cases) <= 10^4- Each triple
[p_a, p_b, p_a_and_b]satisfies0.0 <= p_a <= 1.0,0.0 < p_b <= 1.0, and0.0 <= p_a_and_b <= min(p_a, p_b) - Floating-point values within
10^-6relative or absolute tolerance are accepted
Step-by-step walkthrough
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 collectedrheads in total (they do not need to be consecutive). Compute the expected number of tosses.total_flips(n) andexact_heads(k): toss the coinntimes and compute the probability of seeing exact countkheads.conditional_cases: a list of[P(A), P(B), P(A and B)]triples (withP(B) > 0). For each triple, compute the conditional probabilityP(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, ...].Part 1: Expected tosses until r total heads
Start with the simpler building block: how many tosses
Edoes it take on average to see just1head?You always spend
1toss right away:- With probability
p, that first toss is a head and you stop (0extra 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 needingEmore tosses on average!
Writing that sentence as an equation solves
Ein two lines of algebra:E = 1 + p * 0 + (1 - p) * E E - (1 - p) * E = 1 p * E = 1 --> E = 1 / pFor a fair coin (
p = 0.5),1head takes1 / 0.5 = 2tosses on average. Now slice a run untilrtotal 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 addingrsegments givesr / p(3 / 0.5 = 6.0tosses 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- With probability
Part 2: Probability of exact k heads in n tosses
Suppose we toss a coin
n = 4times and wantk = 3heads, as in Example 1. Look at the matching sequences out of the2^4 = 16outcomes: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.25Why isn't the answer just
p^k * (1 - p)^(n - k)? Because that expression is the probability of one specific ordering (such asHHHTalone)! There areC(n, k)distinct ways to choose whichkof thentoss positions receive the heads, and each of thoseC(n, k)mutually exclusive sequences has probabilityp^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_flipsupfront and return0.0: besides being impossible in real life,math.comb(n, k)raisesValueErrorwhenk < 0, and whenp = 1.0withk > n,(1.0 - p) ** (n - k)evaluates0.0 ** (negative integer), raisingZeroDivisionError.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_probPart 3: Conditional probability and checking independence
Asking for
P(A | B)means: "We already know eventBhappened—among outcomes insideB, what fraction also belong toA?"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)byP(B)rescalesBto become our new100%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. NoticeP(A | B) == P(A)(0.4 == 0.4) becauseP(A) * P(B) = 0.2 = P(A and B)—eventsAandBare 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. HereP(A | B) = 0.4 != P(A) = 0.6, showingAis less likely onceBoccurs—the two events are dependent!
Notice that
P(A)is never used inside the divisionp_a_and_b / p_b; comparingP(A | B)againstP(A)simply tells an analyst whetherBcarries information aboutA.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- Case 1 (
Assemble the combined output list
Now
calculate_probability_answerscalls our three helpers in order: the expected toss count first, the binomial probability second, and then oneP(A | B)entry for each[p_a, p_b, p_a_and_b]triple inconditional_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 answersTrace 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]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:
- Collecting stamps for
rtotal heads: If1in every2coin tosses lands heads (p = 0.5), you expect to spend1 / p = 2tosses 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 forrheads 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 forrtotal heads—a negative binomial distribution—addsrwaits of1 / pto giver / p. - Counting winning seating charts for
kheads inntosses: Each specific sequence ofkheads andn - ktails (such asHHHT) has chancep^k * (1 - p)^(n - k), and there areC(n, k)ways to choose whichktoss slots get the heads, giving the binomial distribution probability mass function (PMF) (a formula assigning the exact probability to each discrete outcome). - Zooming the camera into
Bfor conditional probability: Conditional probabilityP(A | B)asks what share ofB's world also falls insideA, so we divide their overlapP(A and B)byP(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 (plusO(1)arithmetic for smalln).expected_flips_until_headsis a single division,conditional_probabilityperforms one division for each of themcases, andbinomial_probabilityperforms onemath.comb(n, k)call and two exponentiations (constant time for typicaln, scaling withnifngrows into large big-integer factorials). - Space:
O(m). Aside from a handful of scalar variables, memory goes solely to the returnedanswerslist of lengthm + 2.
Edge cases
- Impossible head counts (
exact_heads < 0orexact_heads > total_flips): Returns0.0immediately, avoidingValueErrorinmath.combfor negativekandZeroDivisionErrorfrom0.0 ** (n - k)whenp = 1.0andk > n. - Zero heads or all heads (
k = 0ork = n):C(n, 0) = C(n, n) = 1, cleanly returning(1 - p)^norp^n. - Zero tosses (
n = 0, k = 0): Python evaluates0.0 ** 0as1.0, so0tosses yield0heads with probability1.0. - Guaranteed heads (
p = 1.0):rheads taker / 1.0 = rtosses,P(X = n) = 1.0, andP(X = k) = 0.0fork < n. - Subset and disjoint conditional cases: When
Blies completely insideA(P(A and B) == P(B)),P(A | B) = 1.0; whenAandBare disjoint events (mutually exclusive events that can never happen together, soP(A and B) == 0),P(A | B) = 0.0. - Empty
conditional_cases([]): Returns just[expected_flips, exact_k_prob]. - Large
nfloat overflow (n >= 1030):math.comb(1030, 515)exceeds IEEE-754 double precision (~1.8e308), raisingOverflowErrorwhen multiplied by a float. For hugenand0 < p < 1, compute in log space using log-gamma (math.lgamma(x)computesln((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.5take2 / 0.5 = 4tosses on average becauseHTHfinishes on toss3, whereas two consecutive headsHHtake6tosses because a tail after one head resets your streak. - Multiplying instead of dividing (
r * porr / (1 - p)): Sanity-check with a rare coin likep = 0.01—a rarer head must require more tosses (100per head, not0.01), confirmingpbelongs in the denominator. - Forgetting
C(n, k)in the binomial probability: Reportingp^k * (1 - p)^(n - k)counts only one fixed ordering of heads and tails instead of allC(n, k)orderings. - Dividing by
P(A)instead ofP(B):P(A and B) / P(A)computesP(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 haveP(A and B) = 0 != P(A) * P(B), meaning they are maximally dependent (ifBhappened,Adefinitely 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 (0heads vs1trailing head) and letE0andE1be the expected remaining tosses from each state. From streak0, one toss moves you to streak1with probabilitypor leaves you at0with probability1 - p(E0 = 1 + p * E1 + (1 - p) * E0); from streak1, a head finishes immediately while a tail resets you back to0(E1 = 1 + (1 - p) * E0). SubstitutingE1intoE0yieldsE0 = (1 + p) / p^2 = 1/p + 1/p^2, which is2 + 4 = 6tosses for a fair coin instead of2 / 0.5 = 4tosses for two non-consecutive heads. - What are the variance and standard deviation of the total flips needed to collect
rnon-consecutive heads? A single geometric wait until one head has variance(1 - p) / p^2. Because thersegments between consecutive heads are mutually independent, their variances sum directly:Var(T) = r * (1 - p) / p^2, and the standard deviation issqrt(Var(T)). For Example 1 (p = 0.5, r = 3),Var(T) = 3 * 0.5 / 0.25 = 6.0, giving a standard deviation ofsqrt(6) ≈ 2.45tosses around the mean of6.0. - How would you verify these closed-form probability answers with a Monte Carlo check in Python? Simulate
N = 100,000independent trials withrandom.random() < pand compare the empirical average against the analytical answer using the standard error (SD / sqrt(N), the typical random fluctuation of a sample average overNtrials). Forp = 0.5, r = 3(SD ≈ 2.45), the standard error over100,000runs is2.45 / sqrt(100,000) ≈ 0.0077, so a valid simulation mean will almost always fall within±0.03(~4standard errors) of6.0, immediately exposing formula errors.
Follow-up questions
- How does the expected flip count change if the required two heads must appear back to back (`HH`)?
- What are the variance and standard deviation of the total flips needed to collect `r` non-consecutive heads?
- How would you verify these closed-form probability answers with a Monte Carlo check in Python?
Similar questions
- Spark APIs, MapReduce Trade-Offs, and Cloud Cluster Operations
- Apache Spark APIs and Lazy Evaluation Speedups
- Longest Strictly Increasing Subsequence
- Feature Scaling, PCA, Backpropagation, and Classification Thresholds
- Handling an Inconclusive A/B Test Readout
- Ad Serving Economics, Mixture Variance, and Waiting Times