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 <= 100 and 0 <= b <= 100 (a and b are integer percentages; if a == 0 and b == 0, observing red items is impossible and raising ValueError is expected).
  • k >= 1 is 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

  1. 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 probability a / 100). - Plant B: b% red (each single draw is red with probability b / 100).

    We flip a fair coin (1/2 chance for A, 1/2 chance for B) to select one plant, then draw k items from that selected plant. Every one of those k items is red. We want the conditional probability P(Plant A | all k items are red) as a float.

    Because each plant's output run is effectively infinite, conditioned on which plant was selected, the k draws are mutually independent — observing one red item does not alter the red proportion on subsequent draws from that same plant.

  2. 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 inspection 1,000 times:

                            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 samples
    

    When we learn that all 2 inspected items were red, every inspection containing any black item is eliminated. Exactly 320 + 80 = 400 inspections remain, and 320 of them came from Plant A:

    P(A | 2 red) = 320 / (320 + 80) = 320 / 400 = 4 / 5 = 0.8
    
  3. Derive the general formula with Bayes' rule

    Now convert that two-branch frequency tree into an exact formula for general a, b, and k:

    1. Likelihood under each plant (probability of k consecutive 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
    2. Multiply by the prior (1/2 for each plant):
      • P(A and all k red) = (1/2) * (a / 100)^k
      • P(B and all k red) = (1/2) * (b / 100)^k
    3. Normalize A's joint probability by the total probability of k reds (Bayes' rule):
    P(A | all k red) =               (1/2) * (a / 100)^k
                       -----------------------------------------------
                       (1/2) * (a / 100)^k  +  (1/2) * (b / 100)^k
    

    Every term on top and bottom shares the common factor (1/2) * (1 / 100)^k. Multiplying numerator and denominator by 2 * 100^k cancels both constants cleanly:

    P(A | all k red) = a^k / (a^k + b^k)
    
  4. Prevent floating-point underflow for large k

    Consider a = 1, b = 1, and k = 500. Since both plants have identical red rates, the true posterior must be 0.5. Yet evaluating (a / 100) ** k directly computes 0.01 ** 500 = 10^-1000, which falls far below the smallest positive 64-bit float (~5e-324). Both terms underflow to 0.0, causing 0.0 / (0.0 + 0.0) to raise ZeroDivisionError!

    We prevent both float underflow and slow multi-thousand-digit integer powers by dividing both a and b by max_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 equals 1.0, total_scaled_likelihood always lies in [1.0, 2.0] — division by zero can never occur! - If the smaller ratio (min_rate / max_rate) ** k underflows to 0.0 at huge k, the true answer is genuinely 1.0 or 0.0 to full 64-bit precision anyway.

    The sole impossible input is a == 0 and b == 0: neither plant ever makes red items, so k >= 1 red draws have zero probability and we raise ValueError.

    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_b
    
  5. Trace 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.035714
    

    In 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 to 0.80; in Example 3, three consecutive red draws heavily favor the 60%-red Plant B, driving Plant A's posterior down to 1/28 ≈ 0.0357.

  6. 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). Computing max(a, b), two float divisions, two hardware floating-point power operations x ** 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, and total_scaled_likelihood) are allocated.

Edge cases

  • Identical red percentages (a == b > 0): Red draws carry zero distinguishing information, so both scaled likelihoods equal 1.0 and the function returns 0.5 for every k (including k = 500).
  • One plant never produces red (a == 0, b > 0 or a > 0, b == 0): Observing even 1 red item eliminates the 0% plant immediately; (0 / max_rate) ** k is 0.0 for k >= 1, returning 0.0 when a == 0 and 1.0 when b == 0.
  • Neither plant produces red (a == 0 and b == 0): Seeing k >= 1 red items has probability 0, leaving the conditional probability undefined (0 / 0), so we raise ValueError.
  • One plant is 100% red (a = 100, b = 50, k = 1): Resist returning 1.0! Plant B still yields a red item half the time, so Plant A's posterior is 100 / (100 + 50) = 2/3.
  • Large sample sizes (k = 500 or 1000): Scaling by max(a, b) avoids float underflow without allocating multi-kilobyte big integers.

Common mistakes

  • Returning the raw likelihood (a / 100) ** k instead of the posterior: That computes P(all k red | A) rather than normalizing across both plants via Bayes' rule to get P(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 k items; re-picking per draw would make every draw have marginal red rate (a + b) / 200.
  • Raising (a / 100) to power k directly in floats: Underflows to 0.0 / 0.0 whenever max(a, b) < 100 and k is moderately large (0.01 ** 162 == 0.0).
  • Rounding intermediate probabilities: Truncating (a / 100) ** k to two decimal places before dividing severely warps the ratio for larger k; keep full precision throughout.

Alternative approaches

  • Arbitrary-precision integer powers (a ** k / (a ** k + b ** k)): Python int arithmetic never underflows, and true division / between two huge ints converts their ratio cleanly to a float. That works well for small-to-moderate k, though at huge k (e.g., k = 10^6) big-integer exponentiation costs O(k log a) bit operations rather than O(1).
  • Log-space / sigmoid formulation: When a > 0 and b > 0, a^k / (a^k + b^k) equals 1 / (1 + exp(k * (ln(b) - ln(a)))) (branching on the sign of k * (ln(b) - ln(a)) so math.exp never overflows). Log-space is essential when multiplying thousands of heterogeneous likelihoods, while dividing by max(a, b) is simpler here because all k draws 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 r red and k - r black items has likelihood C(k, r) * (a / 100)^r * ((100 - a) / 100)^(k - r), where the binomial coefficient C(k, r) counts how many ways r red positions can be chosen among k draws. Both the 1/2 priors, the 100^k denominators, and C(k, r) cancel out between numerator and denominator, yielding P(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 when a or b equals 0 or 100).
  • How does the formula change when Plant A has an unequal prior selection probability p instead of 1/2? With prior p on Plant A and 1 - p on 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 ratio P(A) / P(B)), the posterior odds equal the prior odds p / (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) > t rearranges into (a / b)^k > t / (1 - t): if t < 0.5 or b == 0 (with t < 1), k = 1 already clears the bar; otherwise taking natural logs gives k > ln(t / (1 - t)) / ln(a / b), so k = floor(ln(t / (1 - t)) / ln(a / b)) + 1 (with an exact integer check around exact powers such as a = 80, b = 40, t = 0.8, where k = 2 hits 0.8 exactly and k = 3 is needed to strictly exceed 0.8).

Follow-up questions

Similar questions

More SIG (Susquehanna) interview questions

All 44 SIG (Susquehanna) questions →