Posterior Probability of Plant A Given k Red Draws
Medium · Statistics & Math · Quantitative Trader · Online Assessment
Problem Statement
Two manufacturing plants, Plant A and Plant B, produce identical hardware components in two finishes: red and black.
- At Plant A, a% of components produced are red and (100 - a)% are black.
- At Plant B, b% of components produced are red and (100 - b)% are black.
An inspector chooses one of the two plants uniformly at random (probability 1/2 for Plant A and 1/2 for Plant B) and inspects k components drawn from that single chosen plant. Because each plant's output volume is effectively inexhaustible, the k draws are conditionally independent given the chosen plant.
Every single one of the k inspected components turns out to be red. Implement posterior_factory_a(a, b, k) to return the conditional probability that the batch originated from Plant A (P(Plant A | all k items are red)) as a floating-point number.
Examples
Example 1
Input: a = 75, b = 25, k = 1
Output: 0.75
Explanation: Both plants are equally likely beforehand (1/2 each). Drawing 1 red component has probability 0.75 under Plant A and 0.25 under Plant B, so Bayes' rule gives (0.5 * 0.75) / (0.5 * 0.75 + 0.5 * 0.25) = 75 / 100 = 0.75.
Example 2
Input: a = 80, b = 40, k = 2
Output: 0.8
Explanation: Two consecutive red draws occur with probability 0.80^2 = 0.64 under Plant A and 0.40^2 = 0.16 under Plant B. With equal 1/2 priors, Plant A's posterior probability is 0.64 / (0.64 + 0.16) = 0.64 / 0.80 = 0.8.
Example 3
Input: a = 20, b = 60, k = 3
Output: 0.03571428571428571
Explanation: Three red draws have relative weight 20^3 = 8,000 under Plant A versus 60^3 = 216,000 under Plant B, giving 8,000 / (8,000 + 216,000) = 1 / 28 ≈ 0.035714.
Constraints
0 <= a <= 100and0 <= b <= 100(aandbare integer percentages; ifa == 0andb == 0, observing red items is impossible and raisingValueErroris expected).k >= 1is a positive integer (may be hundreds or more, so guard against floating-point underflow).- Return full floating-point precision (
float) without intermediate rounding.
Step-by-step walkthrough
Understand the experiment and what we want to find
Two manufacturing plants produce identical components in vast runs: - Plant A:
a%red (each single draw is red with probabilitya / 100). - Plant B:b%red (each single draw is red with probabilityb / 100).We flip a fair coin (
1/2chance for A,1/2chance for B) to select one plant, then drawkitems from that selected plant. Every one of thosekitems is red. We want the conditional probabilityP(Plant A | all k items are red)as afloat.Because each plant's output run is effectively infinite, conditioned on which plant was selected, the
kdraws are mutually independent — observing one red item does not alter the red proportion on subsequent draws from that same plant.Visualize 1,000 inspections as a frequency tree
Before writing algebra, let's trace Example 2 (
a = 80,b = 40,k = 2) by imagining we repeat the entire two-stage inspection1,000times:1,000 total inspections / \ (coin = A: 1/2) (coin = B: 1/2) / \ 500 pick Plant A 500 pick Plant B (80% red per draw) (40% red per draw) | | Both red: 0.8 * 0.8 = 0.64 Both red: 0.4 * 0.4 = 0.16 | | 320 all-red samples 80 all-red samplesWhen we learn that all
2inspected items were red, every inspection containing any black item is eliminated. Exactly320 + 80 = 400inspections remain, and320of them came from Plant A:P(A | 2 red) = 320 / (320 + 80) = 320 / 400 = 4 / 5 = 0.8Derive the general formula with Bayes' rule
Now convert that two-branch frequency tree into an exact formula for general
a,b, andk:- Likelihood under each plant (probability of
kconsecutive red draws given a known plant):- Given Plant A:
P(all k red | A) = (a / 100)^k - Given Plant B:
P(all k red | B) = (b / 100)^k
- Given Plant A:
- Multiply by the prior (
1/2for each plant):P(A and all k red) = (1/2) * (a / 100)^kP(B and all k red) = (1/2) * (b / 100)^k
- Normalize A's joint probability by the total probability of
kreds (Bayes' rule):
P(A | all k red) = (1/2) * (a / 100)^k ----------------------------------------------- (1/2) * (a / 100)^k + (1/2) * (b / 100)^kEvery term on top and bottom shares the common factor
(1/2) * (1 / 100)^k. Multiplying numerator and denominator by2 * 100^kcancels both constants cleanly:P(A | all k red) = a^k / (a^k + b^k)- Likelihood under each plant (probability of
Prevent floating-point underflow for large k
Consider
a = 1,b = 1, andk = 500. Since both plants have identical red rates, the true posterior must be0.5. Yet evaluating(a / 100) ** kdirectly computes0.01 ** 500 = 10^-1000, which falls far below the smallest positive 64-bit float (~5e-324). Both terms underflow to0.0, causing0.0 / (0.0 + 0.0)to raiseZeroDivisionError!We prevent both float underflow and slow multi-thousand-digit integer powers by dividing both
aandbbymax_rate = max(a, b)prior to exponentiation:a^k / (a^k + b^k) = (a / max_rate)^k / ( (a / max_rate)^k + (b / max_rate)^k )Why does this guarantee numerical stability? - Whichever plant has the higher red rate evaluates
(max_rate / max_rate) ** k = 1.0 ** k = 1.0. - Because at least one scaled likelihood equals1.0,total_scaled_likelihoodalways lies in[1.0, 2.0]— division by zero can never occur! - If the smaller ratio(min_rate / max_rate) ** kunderflows to0.0at hugek, the true answer is genuinely1.0or0.0to full 64-bit precision anyway.The sole impossible input is
a == 0andb == 0: neither plant ever makes red items, sok >= 1red draws have zero probability and we raiseValueError.if a == 0 and b == 0: raise ValueError("k red parts are impossible when both factories make no red parts") max_rate = max(a, b) scaled_likelihood_a = (a / max_rate) ** k scaled_likelihood_b = (b / max_rate) ** k total_scaled_likelihood = scaled_likelihood_a + scaled_likelihood_bTrace the examples step by step
Let's check our rescaled formula across all three examples from the statement:
Example (a, b, k) max_rate scaled_a scaled_b scaled_a / (scaled_a + scaled_b) ------- ------------ -------- ---------------- ---------------- -------------------------------- 1 (75, 25, 1) 75 (75/75)^1 = 1.0 (25/75)^1 = 1/3 1 / (4/3) = 3/4 = 0.75 2 (80, 40, 2) 80 (80/80)^2 = 1.0 (40/80)^2 = 1/4 1 / (5/4) = 4/5 = 0.8 3 (20, 60, 3) 60 (20/60)^3 = 1/27 (60/60)^3 = 1.0 (1/27)/(28/27) = 1/28 ≈ 0.035714In Example 2, a single red draw would give
80 / 120 = 2/3 ≈ 0.6667, and seeing a second red draw strengthens our belief in Plant A up to0.80; in Example 3, three consecutive red draws heavily favor the60%-red Plant B, driving Plant A's posterior down to1/28 ≈ 0.0357.Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple def posterior_factory_a(a: int, b: int, k: int) -> float: # If neither factory ever produces red parts, observing k >= 1 red parts has probability 0. if a == 0 and b == 0: raise ValueError("k red parts are impossible when both factories make no red parts") # Bayes' rule with equal 1/2 priors simplifies to P(A | all k red) = a^k / (a^k + b^k). # Dividing both rates by max_rate before raising to power k makes the larger base 1.0, # so the denominator is always >= 1.0 and can never underflow to 0.0 / 0.0 for large k. max_rate = max(a, b) scaled_likelihood_a = (a / max_rate) ** k scaled_likelihood_b = (b / max_rate) ** k # Normalize Factory A's scaled likelihood by the combined scaled likelihood of A and B. total_scaled_likelihood = scaled_likelihood_a + scaled_likelihood_b return scaled_likelihood_a / total_scaled_likelihood✅ Submit now — all tests should pass.
Intuition & how it works
Imagine two unlabeled bins of tokens in front of you: Bin A is 80% red and Bin B is 40% red. You flip a fair coin to choose one bin sight unseen, draw k tokens from that same bin, and find that every single token is red. Before drawing anything, each bin has a 50% prior probability (how plausible a hypothesis is before observing evidence). After observing k red tokens, we score each bin by its likelihood (the probability of observing those k red tokens assuming that specific bin was chosen): (a / 100)^k for Plant A versus (b / 100)^k for Plant B. Bayes' rule (the probability theorem that converts priors into updated beliefs by dividing one hypothesis's prior-weighted likelihood by the sum of prior-weighted likelihoods across all hypotheses) combines those scores into the posterior probability (the updated probability of Plant A given the k red draws): a^k / (a^k + b^k).
Why do the two most common shortcuts go wrong? First, returning (a / 100)^k by itself mixes up P(all k red | A) with P(A | all k red) — on a = 80, b = 40, k = 2, (0.8)^2 = 0.64 decreases as k grows, even though seeing more red items makes the redder Plant A more probable (0.80)! Second, computing (a / 100) ** k / ((a / 100) ** k + (b / 100) ** k) directly suffers from floating-point underflow (when a positive number smaller than ~5e-324 rounds down to 0.0 in 64-bit IEEE-754 arithmetic): on a = 1, b = 1, k = 500, both 0.01 ** 500 terms vanish to 0.0 and fail with 0.0 / 0.0, whereas dividing both rates by max(a, b) first sets the larger base to 1.0 so the denominator is always between 1.0 and 2.0.
Here is how 1,000 imaginary inspections play out on Example 2 (a = 80, b = 40, k = 2):
1. Coin flip (prior 1/2 each): 500 runs pick Plant A, 500 runs pick Plant B
2. Draw k = 2 items:
- Plant A (80% red): 500 * (0.80)^2 = 500 * 0.64 = 320 runs yield 2 red items
- Plant B (40% red): 500 * (0.40)^2 = 500 * 0.16 = 80 runs yield 2 red items
3. Restrict to all-red runs: 320 + 80 = 400 surviving runs
4. Plant A's share: 320 / 400 = 4 / 5 = 0.8
Our rescaled code computes the exact same 4 / 5 = 0.8 via max_rate = 80, scaled_likelihood_a = (80 / 80)^2 = 1.0, scaled_likelihood_b = (40 / 80)^2 = 0.25, and 1.0 / (1.0 + 0.25) = 0.8.
Complexity
- Time:
O(1). Computingmax(a, b), two float divisions, two hardware floating-point power operationsx ** k, one addition, and one final division executes a fixed number of constant-time arithmetic operations for any inputs. - Space:
O(1). Only four scalar variables (max_rate,scaled_likelihood_a,scaled_likelihood_b, andtotal_scaled_likelihood) are allocated.
Edge cases
- Identical red percentages (
a == b > 0): Red draws carry zero distinguishing information, so both scaled likelihoods equal1.0and the function returns0.5for everyk(includingk = 500). - One plant never produces red (
a == 0, b > 0ora > 0, b == 0): Observing even1red item eliminates the0%plant immediately;(0 / max_rate) ** kis0.0fork >= 1, returning0.0whena == 0and1.0whenb == 0. - Neither plant produces red (
a == 0 and b == 0): Seeingk >= 1red items has probability0, leaving the conditional probability undefined (0 / 0), so we raiseValueError. - One plant is 100% red (
a = 100, b = 50, k = 1): Resist returning1.0! Plant B still yields a red item half the time, so Plant A's posterior is100 / (100 + 50) = 2/3. - Large sample sizes (
k = 500or1000): Scaling bymax(a, b)avoids float underflow without allocating multi-kilobyte big integers.
Common mistakes
- Returning the raw likelihood
(a / 100) ** kinstead of the posterior: That computesP(all k red | A)rather than normalizing across both plants via Bayes' rule to getP(A | all k red). - Assuming the plant is re-chosen on every draw: A single coin flip selects one plant for the entire sample of
kitems; re-picking per draw would make every draw have marginal red rate(a + b) / 200. - Raising
(a / 100)to powerkdirectly in floats: Underflows to0.0 / 0.0whenevermax(a, b) < 100andkis moderately large (0.01 ** 162 == 0.0). - Rounding intermediate probabilities: Truncating
(a / 100) ** kto two decimal places before dividing severely warps the ratio for largerk; keep full precision throughout.
Alternative approaches
- Arbitrary-precision integer powers (
a ** k / (a ** k + b ** k)): Pythonintarithmetic never underflows, and true division/between two hugeints converts their ratio cleanly to afloat. That works well for small-to-moderatek, though at hugek(e.g.,k = 10^6) big-integer exponentiation costsO(k log a)bit operations rather thanO(1). - Log-space / sigmoid formulation: When
a > 0andb > 0,a^k / (a^k + b^k)equals1 / (1 + exp(k * (ln(b) - ln(a))))(branching on the sign ofk * (ln(b) - ln(a))somath.expnever overflows). Log-space is essential when multiplying thousands of heterogeneous likelihoods, while dividing bymax(a, b)is simpler here because allkdraws share one base rate.
Follow-up questions
- What is the updated probability for Plant A if the sample of size k contains mixed colors—specifically r red items and k - r black items? Under Plant A, observing
rred andk - rblack items has likelihoodC(k, r) * (a / 100)^r * ((100 - a) / 100)^(k - r), where the binomial coefficientC(k, r)counts how many waysrred positions can be chosen amongkdraws. Both the1/2priors, the100^kdenominators, andC(k, r)cancel out between numerator and denominator, yieldingP(A | r red, k - r black) = a^r * (100 - a)^(k - r) / (a^r * (100 - a)^(k - r) + b^r * (100 - b)^(k - r))(handling boundary cases whenaorbequals0or100). - How does the formula change when Plant A has an unequal prior selection probability p instead of 1/2? With prior
pon Plant A and1 - pon Plant B, the prior weights no longer cancel, so each likelihood stays weighted by its prior:P(A | all k red) = (p * a^k) / (p * a^k + (1 - p) * b^k). Expressed in odds (the ratioP(A) / P(B)), the posterior odds equal the prior oddsp / (1 - p)multiplied by the likelihood ratio(a / b)^k. - Assuming a > b, what is the minimum run length k of red items required to push Plant A's posterior probability strictly above a threshold t? Requiring
a^k / (a^k + b^k) > trearranges into(a / b)^k > t / (1 - t): ift < 0.5orb == 0(witht < 1),k = 1already clears the bar; otherwise taking natural logs givesk > ln(t / (1 - t)) / ln(a / b), sok = floor(ln(t / (1 - t)) / ln(a / b)) + 1(with an exact integer check around exact powers such asa = 80, b = 40, t = 0.8, wherek = 2hits0.8exactly andk = 3is needed to strictly exceed0.8).
Follow-up questions
- What is the updated probability for Plant A if the sample of size k contains mixed colors—specifically r red items and k - r black items?
- How does the formula change when Plant A has an unequal prior selection probability p instead of 1/2?
- Assuming a > b, what is the minimum run length k of red items required to push Plant A's posterior probability strictly above a threshold t?
Similar questions
- Knights and Knaves Two-Claim Deductions
- Expected Payout of a Two-Dice Roll Game
- Expected Die Rolls for Stopping Patterns
- Conditional Age-Bracket Probability Given Cycling
- Goal-Reaching Probability Under Bold Wagering
- Muffin Inventory Sufficiency Probability
More SIG (Susquehanna) interview questions
- Expected Payout of a Two-Dice Roll Game Easy
- Conditional Age-Bracket Probability Given Cycling Easy
- Probability of Concurrent Bloom Windows Easy Pro
- Posterior Probability Given a Losing Rabbit Easy Pro
- Cookie Assortment Combination Counts Easy Pro
- Streaming Equal-Step Triple Counts Under Updates Medium Pro
- Grid Paths Without Triple Consecutive Steps Easy Pro
- Cat Ownership Puzzle Under Comparative Honesty Rules Easy Pro
- FIFO Inventory Register with Atomic Checkouts Easy Pro
- Count Ants from Total Leg Observations Easy Pro