Quantitative Probability and Combinatorics Toolkit

Hard · Software Engineering Fundamentals · Quantitative Trader · Online Assessment

Problem Statement

Implement a collection of exact discrete-mathematics, probability, expectation, Bayesian-inference, and logical-deduction functions using int and fractions.Fraction (so rational results never suffer floating-point rounding):

  1. Combinatorial Counting

    • count_arrangements(word) — Return the number of distinct strings obtainable by permuting all characters of word ("" yields 1).
    • numbers_from_pairwise_sums(s1, s2, s3) — Given the three pairwise sums x + y, x + z, and y + z of three unknown numbers, return [x, y, z] sorted in non-decreasing order as Fraction values.
    • count_rectangles(rows, cols) — Return how many axis-aligned rectangles (squares included) formed of whole unit cells exist inside a rows × cols grid.
  2. Sampling Without Replacement

    • distinct_color_probabilities(counts, draws) — An urn holds counts[i] indistinguishable tokens of category i. Sample draws tokens uniformly without replacement and return {k: prob} mapping each achievable distinct-category count k (including only keys with prob > 0) to its exact Fraction probability. Raise ValueError if draws < 0, any entry in counts is negative, or draws > sum(counts).
  3. Contest Wagering & Expected Net Profit

    • exact_order_bet_value(horses, places, cost, payout) — In a contest of horses entrants whose horses! finishing orders are equally likely, paying upfront fee cost awards gross prize payout when your predicted 1st-through-places-th finishers match in exact sequence (and 0 otherwise). Return expected net profit (expected_gross_return - cost).
    • horse_option_values() — For a 5-entrant uniform contest, return expected net profits for "a" through "e": "a", "b", "c", and "d" pay upfront fees 10, 20, 30, and 60 to predict the exact top 5, 4, 3, and 2 finishers respectively for gross prize 1000, while "e" takes a guaranteed Fraction(10) net profit without wagering.
  4. Sequential Stopping & Accumulation

    • even_stop_probability(sides=2) — Roll an independent fair sides-faced die (1..sides) repeatedly until the newest roll matches the immediately preceding roll for the first time. Return the probability that the total roll count upon stopping is even. Raise ValueError if sides < 1.
    • expected_flips_given_fewer(p_heads=Fraction(1, 2)) — Two independent players each toss a biased coin (landing heads with probability p_heads) until seeing their own first heads. Conditioned on Player 1 finishing in strictly fewer tosses than Player 2, return Player 1's expected toss count. Raise ValueError unless 0 < p_heads < 1.
    • coupon_collector_cost(types, price) — Blind packs cost price each and independently yield one uniformly distributed design out of types designs. Return the expected total spend needed to collect all types designs (0 when types == 0). Raise ValueError if types < 0.
    • reroll_expected_payout(sides=6, threshold=3) — Roll a fair sides-faced die (1..sides) and add the outcome to a running score; roll again whenever the latest face satisfies face > threshold, stopping once face <= threshold. Return the expected final score. Raise ValueError if sides < 1 or threshold < 1.
  5. Bayesian Updating & Conditional Sampling

    • disease_given_positive(prevalence, sensitivity, false_positive_rate) — Given prior probability prevalence, true-positive rate sensitivity, and false_positive_rate among unaffected individuals, return the posterior probability of having the condition given a positive test.
    • box_posterior(boxes, draws, chosen) — One container is selected uniformly from boxes, where boxes[i] = (target_count, total_count). Sampling draws items without replacement from that container yields draws target items. Return the posterior probability that boxes[chosen] was picked, raising ValueError if every container has zero probability of producing that observation.
    • second_white_probability(total_balls) — An urn holds total_balls items, exactly half of which are white, and items are drawn without replacement. Given the first item drawn is white, return the exact probability that the second item is also white. Raise ValueError if total_balls < 2 or total_balls is odd.
  6. Uniform Dice & Arithmetic Triples

    • strictly_increasing_probability(dice=3, sides=6) — Roll dice independent fair sides-faced dice (1..sides) in sequence and return the probability that the recorded values are strictly ascending.
    • leading_digit_one_probability(dice=3, sides=6) — Roll dice independent fair sides-faced dice (1..sides) and return the probability that the base-10 string of the product of all rolled faces starts with "1".
    • average_triple_probability(n=30) — Choose 3 distinct integers uniformly without replacement from 1..n and return the probability that one chosen integer equals the arithmetic mean of the other two. Raise ValueError if n < 3.
  7. Speaker Role Deduction

    • consistent_role_assignments() and true_statement_count() — Four speakers at indices 0, 1, 2, 3 hold a permutation of ("knight", "liar", "jester", "child"). "knight" always makes a true claim; "liar" always makes a false claim; "jester" cannot stand at index 0 and speaks truthfully iff speaker i - 1 spoke falsely; "child" cannot stand at index 0 and speaks truthfully iff speaker i - 1 spoke truthfully. Claims by index: 0 claims "jester", 1 claims not "knight", 2 claims "knight", and 3 claims not "liar". Return all valid role 4-tuples in consistent_role_assignments(), and return how many claims are true under the unique solution in true_statement_count() (raising ValueError if not unique).

Examples

Example 1

Input:
  count_arrangements("LEVEL")
  numbers_from_pairwise_sums(14, 19, 23)
  count_rectangles(3, 4)
  distinct_color_probabilities([2, 3, 1], 2)
Output:
  30
  [Fraction(5, 1), Fraction(9, 1), Fraction(14, 1)]
  60
  {1: Fraction(4, 15), 2: Fraction(11, 15)}

Walk-through: "LEVEL" has 5! / (2! · 2! · 1!) = 30 distinct permutations. Adding 14 + 19 + 23 = 56 counts x + y + z twice (28), yielding [5, 9, 14]. A 3 × 4 grid has C(4, 2) · C(5, 2) = 6 · 10 = 60 rectangles. Out of C(6, 2) = 15 pairs from [2, 3, 1], 1 + 3 + 0 = 4 pairs share one category (4/15) and 11 use two (11/15).

Example 2

Input:
  exact_order_bet_value(4, 2, 15, 120)
  even_stop_probability(3)
  expected_flips_given_fewer(Fraction(1, 3))
  coupon_collector_cost(4, 6)
  reroll_expected_payout(4, 2)
Output:
  Fraction(-5, 1)
  Fraction(3, 5)
  Fraction(9, 5)
  Fraction(50, 1)
  Fraction(5, 1)

Walk-through: Naming top 2 of 4 wins with probability 1/12, so 120/12 - 15 = -5. A 3-sided die matches the prior roll with chance 1/3, giving (1/3) / (1 - 4/9) = 3/5 even-stop probability. With p_heads = 1/3, a synchronized round resolves with probability 1 - (2/3)^2 = 5/9, taking 9/5 rounds on average. Collecting 4 designs takes 1 + 4/3 + 2 + 4 = 25/3 packs (25/3 · 6 = 50). A 4-sided die with threshold = 2 averages 5/2 per roll and re-rolls half the time, yielding (5/2) / (1/2) = 5.

Example 3

Input:
  disease_given_positive(Fraction(2, 100), Fraction(95, 100), Fraction(4, 100))
  box_posterior([(10, 10), (4, 8), (0, 6)], 2, 0)
  second_white_probability(10)
  strictly_increasing_probability(2, 4)
  leading_digit_one_probability(2, 4)
  average_triple_probability(10)
  true_statement_count()
Output:
  Fraction(95, 291)
  Fraction(14, 17)
  Fraction(4, 9)
  Fraction(3, 8)
  Fraction(1, 4)
  Fraction(1, 6)
  3

Walk-through: Out of 10,000 people (200 affected), 190 are true positives and 392 are false positives (190/582 = 95/291). Container likelihoods for 2 target items are 1, 6/28 = 3/14, and 0, giving 1 / (17/14) = 14/17. After drawing 1 of 5 white items from 10, 4/9 remain white. Two 4-sided dice ascend in C(4, 2)/16 = 3/8 of outcomes and start with "1" on (1,1), (3,4), (4,3), (4,4) (4/16 = 1/4). In 1..10, C(5,2) + C(5,2) = 20 of C(10,3) = 120 triples (1/6) form an arithmetic progression, and the unique role assignment ("liar", "jester", "knight", "child") produces 3 true claims.

Constraints

  • Return exact int or fractions.Fraction objects rather than float approximations.
  • 0 <= len(word) <= 20; 1 <= rows, cols <= 10^4
  • 0 <= draws <= sum(counts) <= 30 for valid distinct_color_probabilities calls
  • 1 <= places <= horses <= 15
  • 1 <= dice <= 6 and 1 <= sides <= 10 for explicit enumeration functions; n >= 3 for average_triple_probability

Step-by-step walkthrough

  1. Organize the toolkit around reusable probability patterns

    Although the module spans combinatorics, urn draws, expected values, Bayesian inference, dice enumeration, and logic deduction, every function reduces to a small set of clean analytical ideas. Throughout solution.py, we return int or fractions.Fraction (exact numerator/denominator pairs like Fraction(4, 15)) so floating-point rounding never masks a reasoning slip.

    from typing import Dict, List, Tuple
    from fractions import Fraction
    import itertools
    import math
    
    # ROLES: fixed tuple of the four speaker roles in the deduction puzzle
    ROLES = ("knight", "liar", "jester", "child")
    
  2. Counting by symmetry and boundary lines

    count_arrangements(word). Take "LEVEL" from Example 1: L appears 2 times, E appears 2 times, and V appears 1 time (5 characters total). If identical letters carried tiny numbered tags (L1, L2 and E1, E2), all 5! = 120 permutations would look distinct. Removing the tags collapses 2! swaps of the Ls and 2! swaps of the Es into one string:

    5! / (2! * 2! * 1!) = 120 / (2 * 2 * 1) = 30
    

    numbers_from_pairwise_sums(s1, s2, s3). Trace (14, 19, 23) from Example 1. Instead of isolating one variable at a time, sum all three pairwise equations:

      (x + y) = 14
    + (x + z) = 19
    + (y + z) = 23
    --------------
    2*(x + y + z) = 56   =>   x + y + z = 28
    

    Every unknown appears in exactly two pairs! Subtracting each pairwise sum from 28 yields 28 - 23 = 5, 28 - 19 = 9, and 28 - 14 = 14. Using Fraction(s1 + s2 + s3, 2) also handles odd totals such as (1, 1, 1) -> [1/2, 1/2, 1/2].

    count_rectangles(rows, cols). A grid of 3 rows by 4 columns (Example 1) is bounded by 4 horizontal lines (H0..H3) and 5 vertical lines (V0..V4):

       V0   V1   V2   V3   V4
    H0 +----+----+----+----+
       |    |    |    |    |
    H1 +----+----+----+----+
       |    |    |    |    |
    H2 +----+----+----+----+
       |    |    |    |    |
    H3 +----+----+----+----+
    

    Choosing any 2 horizontal lines (top and bottom edges) and any 2 vertical lines (left and right edges) uniquely frames one axis-aligned rectangle (including squares): C(4, 2) * C(5, 2) = 6 * 10 = 60.

    def count_arrangements(word: str) -> int:
        """Problem 1: number of distinct orderings of the letters of word."""
        # letter_counts: maps each character -> frequency, e.g. {'L': 2, 'E': 2, 'V': 1}
        letter_counts: Dict[str, int] = {}
        for letter in word:
            letter_counts[letter] = letter_counts.get(letter, 0) + 1
    
        # Start with n! orderings as if identical letters wore distinct labels,
        # then divide out k! for each letter repeated k times (exact integer division).
        arrangements = math.factorial(len(word))
        for count in letter_counts.values():
            arrangements //= math.factorial(count)
        return arrangements
    
    
    def numbers_from_pairwise_sums(s1: int, s2: int, s3: int) -> List[Fraction]:
        """Problem 2: the three numbers whose pairwise sums are s1, s2, s3, sorted ascending."""
        # Adding (x + y) + (x + z) + (y + z) counts every number twice: 2 * (x + y + z).
        # Using Fraction handles odd totals cleanly (e.g. sums 1, 1, 1 -> [1/2, 1/2, 1/2]).
        sum_of_all_three = Fraction(s1 + s2 + s3, 2)
    
        # Subtracting each pairwise sum leaves the single number omitted from that pair.
        first = sum_of_all_three - s1
        second = sum_of_all_three - s2
        third = sum_of_all_three - s3
        return sorted([first, second, third])
    
    
    def count_rectangles(rows: int, cols: int) -> int:
        """Problem 12: rectangles (squares included) made of whole cells of a rows x cols board."""
        # A grid of `rows` cells high has `rows + 1` horizontal boundary lines (and `cols + 1` vertical).
        # Any 2 horizontal lines and any 2 vertical lines uniquely frame one axis-aligned rectangle.
        horizontal_line_pairs = math.comb(rows + 1, 2)
        vertical_line_pairs = math.comb(cols + 1, 2)
        return horizontal_line_pairs * vertical_line_pairs
    
  3. Sampling tokens without replacement

    Trace counts = [2, 3, 1] with draws = 2 from Example 1 (6 tokens in total). Labeling the tokens 1..6 gives C(6, 2) = 15 equally likely 2-token subsets:

    • Single category (k = 1): C(2, 2) + C(3, 2) + C(1, 2) = 1 + 3 + 0 = 4 subsets -> 4/15.
    • Two categories (k = 2): pick one token from each of two categories (2*3 + 2*1 + 3*1 = 6 + 2 + 3 = 11 subsets, or 15 - 4 = 11) -> 11/15.

    In general, we enumerate every per-category draw vector picks with 0 <= picks[i] <= min(counts[i], draws) whose entries sum to draws, multiply C(available, picked) across categories, and accumulate counts by how many categories had picked > 0.

    def distinct_color_probabilities(counts: List[int], draws: int) -> Dict[int, Fraction]:
        """Problems 3-4: {k: P(exactly k distinct colors)} when drawing without replacement."""
        if draws < 0 or any(count < 0 for count in counts):
            raise ValueError("counts and draws must be non-negative")
    
        total_items = sum(counts)
        total_ways = math.comb(total_items, draws)
        if total_ways == 0:
            raise ValueError("cannot draw more items than the bag holds")
    
        # per_color_ranges[i]: valid draw counts 0..min(counts[i], draws) from color i
        per_color_ranges = [range(min(count, draws) + 1) for count in counts]
    
        # ways_by_colors: maps distinct_color_count k -> total number of item subsets with k colors
        ways_by_colors: Dict[int, int] = {}
        for picks in itertools.product(*per_color_ranges):
            if sum(picks) != draws:
                continue
    
            # Multiply combinations across colors; since 0 <= picked <= count, ways_for_split >= 1,
            # which guarantees we only record color counts k that have strictly positive probability.
            ways_for_split = 1
            distinct_colors = 0
            for available, picked in zip(counts, picks):
                ways_for_split *= math.comb(available, picked)
                if picked > 0:
                    distinct_colors += 1
            ways_by_colors[distinct_colors] = ways_by_colors.get(distinct_colors, 0) + ways_for_split
    
        probabilities: Dict[int, Fraction] = {}
        for distinct_colors, ways in ways_by_colors.items():
            probabilities[distinct_colors] = Fraction(ways, total_ways)
        return probabilities
    
  4. Contest wagers and expected net profit

    With horses entrants and uniform finishing permutations, there are P(horses, places) = horses * (horses - 1) * ... * (horses - places + 1) equally likely ordered prefixes of length places. In Example 2 (horses = 4, places = 2, cost = 15, payout = 120), P(4, 2) = 12, so expected net profit is 120 / 12 - 15 = -5.

    Evaluating horse_option_values() across the 5-entrant contest (5! = 120):

    "a" (top 5, fee 10): 1000 / 120 - 10 =  25/3 - 10 =  -5/3
    "b" (top 4, fee 20): 1000 / 120 - 20 =  25/3 - 20 = -35/3  (top 4 fixes the 5th!)
    "c" (top 3, fee 30): 1000 / 60  - 30 =  50/3 - 30 = -40/3
    "d" (top 2, fee 60): 1000 / 20  - 60 =  50   - 60 = -10
    "e" (no wager):                                     +10
    
    def exact_order_bet_value(horses: int, places: int, cost: int, payout: int) -> Fraction:
        """Problem 5: expected profit of paying `cost` to name the first `places` finishers in order."""
        # Every ordered list of the top `places` finishers is equally likely: P(horses, places) outcomes.
        ordered_outcomes = math.perm(horses, places)
        expected_return = Fraction(payout, ordered_outcomes)
        return expected_return - cost
    
    
    def horse_option_values() -> Dict[str, Fraction]:
        """Problem 5: expected profit of each option "a".."e" ("e" = walk away with $10)."""
        return {
            "a": exact_order_bet_value(5, 5, 10, 1000),
            "b": exact_order_bet_value(5, 4, 20, 1000),
            "c": exact_order_bet_value(5, 3, 30, 1000),
            "d": exact_order_bet_value(5, 2, 60, 1000),
            "e": Fraction(10),
        }
    
  5. Stopping parity and synchronized coin races

    even_stop_probability(sides). Roll 1 merely establishes the current face; it can never halt the process. From roll 2 onward, each roll independently matches the previous roll with probability m = 1/sides (stopping immediately) or misses with q = 1 - m. Stopping on n = 2, 4, 6, ... gives the geometric series m + q^2 * m + q^4 * m + ... = m / (1 - q^2). On Example 2 (sides = 3), m = 1/3 and q = 2/3, yielding (1/3) / (1 - 4/9) = 3/5 (and 2/3 when sides = 2).

    expected_flips_given_fewer(p_heads). Pair Player 1 and Player 2 in synchronized rounds 1, 2, 3, ... (p = p_heads, q = 1 - p):

    Round outcome       Probability    Effect on the race
    -----------------------------------------------------------------------
    (Tails, Tails)         q * q       Neither finished -> continue to next round
    (Heads, Tails)         p * q       Decisive round: Player 1 wins strictly
    (Tails, Heads)         q * p       Decisive round: Player 2 wins strictly
    (Heads, Heads)         p * p       Decisive round: Tie
    

    Rounds repeat only while both players flip tails (q^2), so the index of the decisive round is geometric with success probability 1 - q^2 and mean 1 / (1 - q^2). Because which decisive outcome ends the race is independent of how many (Tails, Tails) rounds preceded it, conditioning on (Heads, Tails) leaves the round distribution unchanged! For p_heads = 1/3 (Example 2), 1 / (1 - 4/9) = 9/5 (and 4/3 for p_heads = 1/2).

    def even_stop_probability(sides: int = 2) -> Fraction:
        """Problem 6: flip (or roll a fair `sides`-sided die) until two consecutive results are equal."""
        if sides < 1:
            raise ValueError("need at least one side")
    
        # Flip 1 sets the initial value. From flip 2 onward, each flip matches the previous flip
        # with probability 1/sides. Stopping on n = 2, 4, 6, ... sums to match / (1 - miss^2).
        prob_match = Fraction(1, sides)
        prob_miss = 1 - prob_match
        return prob_match / (1 - prob_miss * prob_miss)
    
    
    def expected_flips_given_fewer(p_heads: Fraction = Fraction(1, 2)) -> Fraction:
        """Problem 13: E[Alice's flips | Alice needs fewer flips than Bob]; both flip until first heads."""
        # At p_heads == 1 both stop on flip 1 (tie), so Alice can never finish strictly earlier.
        if not (0 < p_heads < 1):
            raise ValueError("p_heads must be strictly between 0 and 1")
    
        # Pair Alice and Bob in simultaneous rounds. Rounds continue only while BOTH flip tails;
        # conditioning on the first decisive round being (Alice H, Bob T) keeps the round count
        # geometric with success probability 1 - P(both tails).
        prob_both_tails = (1 - p_heads) * (1 - p_heads)
        prob_decisive_round = 1 - prob_both_tails
        return Fraction(1, 1) / prob_decisive_round
    
  6. Phase-by-phase collection and first-step renewal

    coupon_collector_cost(types, price). Split collection into phases owned = 0, 1, ..., types - 1. When you already hold owned distinct designs, each new pack delivers an unseen design with probability (types - owned) / types, requiring types / (types - owned) packs on average. On Example 2 (types = 4, price = 6):

    owned = 0 -> p = 4/4 -> expected packs = 1
    owned = 1 -> p = 3/4 -> expected packs = 4/3
    owned = 2 -> p = 2/4 -> expected packs = 2
    owned = 3 -> p = 1/4 -> expected packs = 4
    ------------------------------------------------
    Total expected packs = 25/3   =>   Spend at 6 per pack = 50
    

    reroll_expected_payout(sides, threshold). Let E denote the expected total score. On roll 1 you always earn the average of a single die roll ((sides + 1) / 2), and with probability max(sides - threshold, 0) / sides (face > threshold) you start an identical copy of the game adding E more:

    E = mean_single_roll + prob_reroll * E   =>   E = mean_single_roll / (1 - prob_reroll)
    

    For Example 2 (sides = 4, threshold = 2), mean_single_roll = 5/2 and prob_reroll = 2/4 = 1/2, giving (5/2) / (1/2) = 5.

    def coupon_collector_cost(types: int, price: int) -> Fraction:
        """Problem 7: expected total spent to collect all `types` equally likely toys at `price` per box."""
        if types < 0:
            raise ValueError("types must be non-negative")
    
        # Phase `owned`: we have `owned` distinct types, so each new box brings an unseen type
        # with probability (types - owned) / types, taking types / (types - owned) boxes on average.
        expected_boxes = Fraction(0)
        for owned in range(types):
            expected_boxes_for_next = Fraction(types, types - owned)
            expected_boxes += expected_boxes_for_next
        return expected_boxes * price
    
    
    def reroll_expected_payout(sides: int = 6, threshold: int = 3) -> Fraction:
        """Problem 8: roll, add the result, roll again while the result is > threshold. E[total]."""
        # If threshold < 1, every face 1..sides exceeds threshold, so the game never terminates.
        if sides < 1 or threshold < 1:
            raise ValueError("sides and threshold must be at least 1 so the game can terminate")
    
        # By first-step renewal: E = mean_single_roll + P(roll > threshold) * E.
        mean_single_roll = Fraction(sides + 1, 2)
        reroll_faces = max(sides - threshold, 0)
        prob_reroll = Fraction(reroll_faces, sides)
        return mean_single_roll / (1 - prob_reroll)
    
  7. Bayes' rule and conditional urn updates

    disease_given_positive. Trace Example 3 (prevalence = 2%, sensitivity = 95%, false_positive_rate = 4%) on a concrete cohort of 10,000 people:

    10,000 people
     ├──   200 affected   (2%)  -> 95% test + -> 190 true positives
     └── 9,800 unaffected (98%) ->  4% test + -> 392 false positives
                                                 -------------------
                                                 582 total positives
    

    Posterior probability: 190 / 582 = 95/291 ≈ 32.6%.

    box_posterior(boxes, draws, chosen). Under a uniform prior across containers, posterior weights are proportional to each container's likelihood C(target_count, draws) / C(total_count, draws). On Example 3 ([(10, 10), (4, 8), (0, 6)], draws = 2, chosen = 0), likelihoods are 1, C(4, 2)/C(8, 2) = 6/28 = 3/14, and 0, giving 1 / (1 + 3/14) = 14/17.

    second_white_probability(total_balls). Starting with total_balls // 2 white items, removing 1 white item leaves (total_balls // 2) - 1 white items among total_balls - 1 remaining items (4/9 when total_balls = 10, approaching 1/2 as total_balls grows huge).

    def disease_given_positive(prevalence: Fraction, sensitivity: Fraction,
                               false_positive_rate: Fraction) -> Fraction:
        """Problem 9: P(disease | positive test)."""
        # Bayes' rule: divide true-positive rate in the population by total positive rate.
        true_positive_prob = prevalence * sensitivity
        false_positive_prob = (1 - prevalence) * false_positive_rate
        return true_positive_prob / (true_positive_prob + false_positive_prob)
    
    
    def box_posterior(boxes: List[Tuple[int, int]], draws: int, chosen: int) -> Fraction:
        """Problem 16: boxes[i] = (chocolate cookies, total cookies); uniform prior over boxes."""
        # likelihoods[i]: P(all `draws` cookies are chocolate | boxes[i] was picked).
        # Equal priors (1/len(boxes)) cancel between numerator and denominator.
        likelihoods: List[Fraction] = []
        for chocolate_count, total_cookies in boxes:
            ways_all_chocolate = math.comb(chocolate_count, draws)
            ways_any_cookies = math.comb(total_cookies, draws)
            likelihoods.append(Fraction(ways_all_chocolate, ways_any_cookies))
    
        total_likelihood = sum(likelihoods)
        if total_likelihood == 0:
            raise ValueError("observed chocolate draw is impossible for every box")
        return likelihoods[chosen] / total_likelihood
    
    
    def second_white_probability(total_balls: int) -> Fraction:
        """Problem 17: a bag of total_balls balls, half of them white. P(2nd white | 1st white)."""
        if total_balls < 2 or total_balls % 2 == 1:
            raise ValueError("total_balls must be an even integer >= 2")
    
        # After drawing 1 white ball without replacement, (white_balls - 1) white balls remain
        # among (total_balls - 1) remaining balls.
        white_balls = total_balls // 2
        return Fraction(white_balls - 1, total_balls - 1)
    
  8. Dice sample spaces, parity midpoints, and role deduction

    strictly_increasing_probability(dice, sides). Every dice-element subset of {1..sides} can be sorted strictly ascending in exactly 1 way, giving C(sides, dice) / sides^dice (C(4, 2) / 16 = 3/8 in Example 3).

    leading_digit_one_probability(dice, sides). Enumerate all sides^dice ordered tuples and check str(product)[0] == "1". On Example 3 (dice = 2, sides = 4), (1, 1) -> 1, (3, 4) -> 12, (4, 3) -> 12, and (4, 4) -> 16 give 4/16 = 1/4.

    average_triple_probability(n). For a < b < c, b = (a + c) / 2 is an integer if and only if a and c share the same parity (both even or both odd), and each same-parity pair {a, c} pins down a unique midpoint b strictly between them! In 1..10 (5 evens, 5 odds), (C(5, 2) + C(5, 2)) / C(10, 3) = 20 / 120 = 1/6.

    consistent_role_assignments and true_statement_count. Neither "jester" nor "child" can stand at index 0 (no preceding speaker exists): - Index 0 claims "jester": "knight" cannot lie, so index 0 is "liar" (claim 0 is false). - Index 1 claims not "knight": "knight" cannot make that claim truthfully, so claim 1 is true; after a lying index 0, "jester" speaks truthfully, making index 1 "jester". - Index 2 claims "knight": after a truthful index 1, both remaining candidates ("knight", "child") must speak truthfully, forcing index 2 to be "knight" (claim 2 is true). - Index 3 claims not "liar": "child" copies index 2's truthfulness and is indeed not "liar" (claim 3 is true).

    That leaves ("liar", "jester", "knight", "child") with 3 true claims.

    def strictly_increasing_probability(dice: int = 3, sides: int = 6) -> Fraction:
        """Problem 10: P(the dice, read in order, are strictly increasing)."""
        # Every subset of `dice` distinct faces has exactly 1 strictly increasing ordering.
        increasing_rolls = math.comb(sides, dice)
        total_rolls = sides ** dice
        return Fraction(increasing_rolls, total_rolls)
    
    
    def leading_digit_one_probability(dice: int = 3, sides: int = 6) -> Fraction:
        """Problem 11: P(the product of the dice starts with the digit 1)."""
        # Enumerate all sides^dice equally likely ordered rolls (216 for 3 standard dice).
        matching_rolls = 0
        for roll in itertools.product(range(1, sides + 1), repeat=dice):
            product = 1
            for face_value in roll:
                product *= face_value
            if str(product)[0] == "1":
                matching_rolls += 1
        return Fraction(matching_rolls, sides ** dice)
    
    
    def average_triple_probability(n: int = 30) -> Fraction:
        """Problem 15: three distinct numbers from 1..n; P(one of them is the mean of the other two)."""
        if n < 3:
            raise ValueError("need at least 3 numbers")
    
        # For a < b < c, b = (a + c) / 2 is an integer iff a and c share the same parity
        # (both even or both odd), and each such outer pair (a, c) fixes a unique midpoint b.
        even_count = n // 2
        odd_count = n - even_count
        balanced_triples = math.comb(even_count, 2) + math.comb(odd_count, 2)
        return Fraction(balanced_triples, math.comb(n, 3))
    
    
    def statement_is_true(speaker: int, roles: Tuple[str, ...]) -> bool:
        """Evaluate the literal truth of speaker 0..3's claim under role assignment `roles`."""
        role = roles[speaker]
        if speaker == 0:
            return role == "jester"   # Speaker 1: "I am a jester."
        if speaker == 1:
            return role != "knight"   # Speaker 2: "I am not a knight."
        if speaker == 2:
            return role == "knight"   # Speaker 3: "I am the knight."
        return role != "liar"         # Speaker 4: "I am not a liar."
    
    
    def follows_rule(speaker: int, roles: Tuple[str, ...], truths: List[bool]) -> bool:
        """Check whether `truths[speaker]` obeys the truthfulness rule of `roles[speaker]`."""
        role = roles[speaker]
        if role == "knight":
            return truths[speaker]
        if role == "liar":
            return not truths[speaker]
    
        # Both jester and child depend on "the previous speaker", so neither can speak first (index 0).
        if speaker == 0:
            return False
    
        previous_told_truth = truths[speaker - 1]
        if role == "jester":
            return truths[speaker] == (not previous_told_truth)
        return truths[speaker] == previous_told_truth  # child copies previous speaker's truthfulness
    
    
    def consistent_role_assignments() -> List[Tuple[str, ...]]:
        """Problem 14: all permutations of ROLES consistent with every speaker's rule and statement."""
        # Test all 4! = 24 role permutations from speaker 0 to speaker 3.
        valid_assignments: List[Tuple[str, ...]] = []
        for roles in itertools.permutations(ROLES):
            truths = [statement_is_true(speaker, roles) for speaker in range(4)]
            if all(follows_rule(speaker, roles, truths) for speaker in range(4)):
                valid_assignments.append(roles)
        return valid_assignments
    
    
    def true_statement_count() -> int:
        """Problem 14: how many of the four statements are true (the assignment must be unique)."""
        solutions = consistent_role_assignments()
        if len(solutions) != 1:
            raise ValueError(f"expected one consistent assignment, found {len(solutions)}")
    
        unique_roles = solutions[0]
        true_count = 0
        for speaker in range(4):
            if statement_is_true(speaker, unique_roles):
                true_count += 1
        return true_count
    
  9. Complete `solution.py`

    from typing import Dict, List, Tuple
    from fractions import Fraction
    import itertools
    import math
    
    # ROLES: fixed tuple of the four speaker roles in the deduction puzzle
    ROLES = ("knight", "liar", "jester", "child")
    
    
    # ---------- Counting ----------
    
    def count_arrangements(word: str) -> int:
        """Problem 1: number of distinct orderings of the letters of word."""
        # letter_counts: maps each character -> frequency, e.g. {'L': 2, 'E': 2, 'V': 1}
        letter_counts: Dict[str, int] = {}
        for letter in word:
            letter_counts[letter] = letter_counts.get(letter, 0) + 1
    
        # Start with n! orderings as if identical letters wore distinct labels,
        # then divide out k! for each letter repeated k times (exact integer division).
        arrangements = math.factorial(len(word))
        for count in letter_counts.values():
            arrangements //= math.factorial(count)
        return arrangements
    
    
    def numbers_from_pairwise_sums(s1: int, s2: int, s3: int) -> List[Fraction]:
        """Problem 2: the three numbers whose pairwise sums are s1, s2, s3, sorted ascending."""
        # Adding (x + y) + (x + z) + (y + z) counts every number twice: 2 * (x + y + z).
        # Using Fraction handles odd totals cleanly (e.g. sums 1, 1, 1 -> [1/2, 1/2, 1/2]).
        sum_of_all_three = Fraction(s1 + s2 + s3, 2)
    
        # Subtracting each pairwise sum leaves the single number omitted from that pair.
        first = sum_of_all_three - s1
        second = sum_of_all_three - s2
        third = sum_of_all_three - s3
        return sorted([first, second, third])
    
    
    def count_rectangles(rows: int, cols: int) -> int:
        """Problem 12: rectangles (squares included) made of whole cells of a rows x cols board."""
        # A grid of `rows` cells high has `rows + 1` horizontal boundary lines (and `cols + 1` vertical).
        # Any 2 horizontal lines and any 2 vertical lines uniquely frame one axis-aligned rectangle.
        horizontal_line_pairs = math.comb(rows + 1, 2)
        vertical_line_pairs = math.comb(cols + 1, 2)
        return horizontal_line_pairs * vertical_line_pairs
    
    
    # ---------- Drawing without replacement: problems 3, 4 ----------
    
    def distinct_color_probabilities(counts: List[int], draws: int) -> Dict[int, Fraction]:
        """Problems 3-4: {k: P(exactly k distinct colors)} when drawing without replacement."""
        if draws < 0 or any(count < 0 for count in counts):
            raise ValueError("counts and draws must be non-negative")
    
        total_items = sum(counts)
        total_ways = math.comb(total_items, draws)
        if total_ways == 0:
            raise ValueError("cannot draw more items than the bag holds")
    
        # per_color_ranges[i]: valid draw counts 0..min(counts[i], draws) from color i
        per_color_ranges = [range(min(count, draws) + 1) for count in counts]
    
        # ways_by_colors: maps distinct_color_count k -> total number of item subsets with k colors
        ways_by_colors: Dict[int, int] = {}
        for picks in itertools.product(*per_color_ranges):
            if sum(picks) != draws:
                continue
    
            # Multiply combinations across colors; since 0 <= picked <= count, ways_for_split >= 1,
            # which guarantees we only record color counts k that have strictly positive probability.
            ways_for_split = 1
            distinct_colors = 0
            for available, picked in zip(counts, picks):
                ways_for_split *= math.comb(available, picked)
                if picked > 0:
                    distinct_colors += 1
            ways_by_colors[distinct_colors] = ways_by_colors.get(distinct_colors, 0) + ways_for_split
    
        probabilities: Dict[int, Fraction] = {}
        for distinct_colors, ways in ways_by_colors.items():
            probabilities[distinct_colors] = Fraction(ways, total_ways)
        return probabilities
    
    
    # ---------- Expected value of a bet: problem 5 ----------
    
    def exact_order_bet_value(horses: int, places: int, cost: int, payout: int) -> Fraction:
        """Problem 5: expected profit of paying `cost` to name the first `places` finishers in order."""
        # Every ordered list of the top `places` finishers is equally likely: P(horses, places) outcomes.
        ordered_outcomes = math.perm(horses, places)
        expected_return = Fraction(payout, ordered_outcomes)
        return expected_return - cost
    
    
    def horse_option_values() -> Dict[str, Fraction]:
        """Problem 5: expected profit of each option "a".."e" ("e" = walk away with $10)."""
        return {
            "a": exact_order_bet_value(5, 5, 10, 1000),
            "b": exact_order_bet_value(5, 4, 20, 1000),
            "c": exact_order_bet_value(5, 3, 30, 1000),
            "d": exact_order_bet_value(5, 2, 60, 1000),
            "e": Fraction(10),
        }
    
    
    # ---------- Coin flips: problems 6, 13 ----------
    
    def even_stop_probability(sides: int = 2) -> Fraction:
        """Problem 6: flip (or roll a fair `sides`-sided die) until two consecutive results are equal."""
        if sides < 1:
            raise ValueError("need at least one side")
    
        # Flip 1 sets the initial value. From flip 2 onward, each flip matches the previous flip
        # with probability 1/sides. Stopping on n = 2, 4, 6, ... sums to match / (1 - miss^2).
        prob_match = Fraction(1, sides)
        prob_miss = 1 - prob_match
        return prob_match / (1 - prob_miss * prob_miss)
    
    
    def expected_flips_given_fewer(p_heads: Fraction = Fraction(1, 2)) -> Fraction:
        """Problem 13: E[Alice's flips | Alice needs fewer flips than Bob]; both flip until first heads."""
        # At p_heads == 1 both stop on flip 1 (tie), so Alice can never finish strictly earlier.
        if not (0 < p_heads < 1):
            raise ValueError("p_heads must be strictly between 0 and 1")
    
        # Pair Alice and Bob in simultaneous rounds. Rounds continue only while BOTH flip tails;
        # conditioning on the first decisive round being (Alice H, Bob T) keeps the round count
        # geometric with success probability 1 - P(both tails).
        prob_both_tails = (1 - p_heads) * (1 - p_heads)
        prob_decisive_round = 1 - prob_both_tails
        return Fraction(1, 1) / prob_decisive_round
    
    
    # ---------- Expected totals: problems 7, 8 ----------
    
    def coupon_collector_cost(types: int, price: int) -> Fraction:
        """Problem 7: expected total spent to collect all `types` equally likely toys at `price` per box."""
        if types < 0:
            raise ValueError("types must be non-negative")
    
        # Phase `owned`: we have `owned` distinct types, so each new box brings an unseen type
        # with probability (types - owned) / types, taking types / (types - owned) boxes on average.
        expected_boxes = Fraction(0)
        for owned in range(types):
            expected_boxes_for_next = Fraction(types, types - owned)
            expected_boxes += expected_boxes_for_next
        return expected_boxes * price
    
    
    def reroll_expected_payout(sides: int = 6, threshold: int = 3) -> Fraction:
        """Problem 8: roll, add the result, roll again while the result is > threshold. E[total]."""
        # If threshold < 1, every face 1..sides exceeds threshold, so the game never terminates.
        if sides < 1 or threshold < 1:
            raise ValueError("sides and threshold must be at least 1 so the game can terminate")
    
        # By first-step renewal: E = mean_single_roll + P(roll > threshold) * E.
        mean_single_roll = Fraction(sides + 1, 2)
        reroll_faces = max(sides - threshold, 0)
        prob_reroll = Fraction(reroll_faces, sides)
        return mean_single_roll / (1 - prob_reroll)
    
    
    # ---------- Bayes' rule & conditioning: problems 9, 16, 17 ----------
    
    def disease_given_positive(prevalence: Fraction, sensitivity: Fraction,
                               false_positive_rate: Fraction) -> Fraction:
        """Problem 9: P(disease | positive test)."""
        # Bayes' rule: divide true-positive rate in the population by total positive rate.
        true_positive_prob = prevalence * sensitivity
        false_positive_prob = (1 - prevalence) * false_positive_rate
        return true_positive_prob / (true_positive_prob + false_positive_prob)
    
    
    def box_posterior(boxes: List[Tuple[int, int]], draws: int, chosen: int) -> Fraction:
        """Problem 16: boxes[i] = (chocolate cookies, total cookies); uniform prior over boxes."""
        # likelihoods[i]: P(all `draws` cookies are chocolate | boxes[i] was picked).
        # Equal priors (1/len(boxes)) cancel between numerator and denominator.
        likelihoods: List[Fraction] = []
        for chocolate_count, total_cookies in boxes:
            ways_all_chocolate = math.comb(chocolate_count, draws)
            ways_any_cookies = math.comb(total_cookies, draws)
            likelihoods.append(Fraction(ways_all_chocolate, ways_any_cookies))
    
        total_likelihood = sum(likelihoods)
        if total_likelihood == 0:
            raise ValueError("observed chocolate draw is impossible for every box")
        return likelihoods[chosen] / total_likelihood
    
    
    def second_white_probability(total_balls: int) -> Fraction:
        """Problem 17: a bag of total_balls balls, half of them white. P(2nd white | 1st white)."""
        if total_balls < 2 or total_balls % 2 == 1:
            raise ValueError("total_balls must be an even integer >= 2")
    
        # After drawing 1 white ball without replacement, (white_balls - 1) white balls remain
        # among (total_balls - 1) remaining balls.
        white_balls = total_balls // 2
        return Fraction(white_balls - 1, total_balls - 1)
    
    
    # ---------- Small sample spaces & parity: problems 10, 11, 15 ----------
    
    def strictly_increasing_probability(dice: int = 3, sides: int = 6) -> Fraction:
        """Problem 10: P(the dice, read in order, are strictly increasing)."""
        # Every subset of `dice` distinct faces has exactly 1 strictly increasing ordering.
        increasing_rolls = math.comb(sides, dice)
        total_rolls = sides ** dice
        return Fraction(increasing_rolls, total_rolls)
    
    
    def leading_digit_one_probability(dice: int = 3, sides: int = 6) -> Fraction:
        """Problem 11: P(the product of the dice starts with the digit 1)."""
        # Enumerate all sides^dice equally likely ordered rolls (216 for 3 standard dice).
        matching_rolls = 0
        for roll in itertools.product(range(1, sides + 1), repeat=dice):
            product = 1
            for face_value in roll:
                product *= face_value
            if str(product)[0] == "1":
                matching_rolls += 1
        return Fraction(matching_rolls, sides ** dice)
    
    
    def average_triple_probability(n: int = 30) -> Fraction:
        """Problem 15: three distinct numbers from 1..n; P(one of them is the mean of the other two)."""
        if n < 3:
            raise ValueError("need at least 3 numbers")
    
        # For a < b < c, b = (a + c) / 2 is an integer iff a and c share the same parity
        # (both even or both odd), and each such outer pair (a, c) fixes a unique midpoint b.
        even_count = n // 2
        odd_count = n - even_count
        balanced_triples = math.comb(even_count, 2) + math.comb(odd_count, 2)
        return Fraction(balanced_triples, math.comb(n, 3))
    
    
    # ---------- Logical deduction: problem 14 ----------
    
    def statement_is_true(speaker: int, roles: Tuple[str, ...]) -> bool:
        """Evaluate the literal truth of speaker 0..3's claim under role assignment `roles`."""
        role = roles[speaker]
        if speaker == 0:
            return role == "jester"   # Speaker 1: "I am a jester."
        if speaker == 1:
            return role != "knight"   # Speaker 2: "I am not a knight."
        if speaker == 2:
            return role == "knight"   # Speaker 3: "I am the knight."
        return role != "liar"         # Speaker 4: "I am not a liar."
    
    
    def follows_rule(speaker: int, roles: Tuple[str, ...], truths: List[bool]) -> bool:
        """Check whether `truths[speaker]` obeys the truthfulness rule of `roles[speaker]`."""
        role = roles[speaker]
        if role == "knight":
            return truths[speaker]
        if role == "liar":
            return not truths[speaker]
    
        # Both jester and child depend on "the previous speaker", so neither can speak first (index 0).
        if speaker == 0:
            return False
    
        previous_told_truth = truths[speaker - 1]
        if role == "jester":
            return truths[speaker] == (not previous_told_truth)
        return truths[speaker] == previous_told_truth  # child copies previous speaker's truthfulness
    
    
    def consistent_role_assignments() -> List[Tuple[str, ...]]:
        """Problem 14: all permutations of ROLES consistent with every speaker's rule and statement."""
        # Test all 4! = 24 role permutations from speaker 0 to speaker 3.
        valid_assignments: List[Tuple[str, ...]] = []
        for roles in itertools.permutations(ROLES):
            truths = [statement_is_true(speaker, roles) for speaker in range(4)]
            if all(follows_rule(speaker, roles, truths) for speaker in range(4)):
                valid_assignments.append(roles)
        return valid_assignments
    
    
    def true_statement_count() -> int:
        """Problem 14: how many of the four statements are true (the assignment must be unique)."""
        solutions = consistent_role_assignments()
        if len(solutions) != 1:
            raise ValueError(f"expected one consistent assignment, found {len(solutions)}")
    
        unique_roles = solutions[0]
        true_count = 0
        for speaker in range(4):
            if statement_is_true(speaker, unique_roles):
                true_count += 1
        return true_count
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Think of a probability and combinatorics toolkit like a carpenter's workbench: even when 18 functions look unrelated on the surface, nearly every one comes apart cleanly with four foundational ideas:

  1. Count the defining choices rather than every object — instead of scanning rectangles cell by cell or sorting dice rolls one by one, count the decisions that uniquely pin one down (two horizontal and two vertical grid lines, or a subset of dice distinct faces).
  2. Use first-step or stage-by-stage resets — when a random process can repeat indefinitely, examine what happens on one step; memorylessness (the property that future independent rolls or tosses do not depend on how the process arrived at the present state) turns an infinite sum into a one-line linear equation like E = 2.5 + 0.5 * E.
  3. Count a concrete cohort for conditional probability — Bayes' rule (revising the probability of an underlying cause after observing new evidence) becomes transparent when you split a hypothetical crowd of 10,000 people into true positives and false positives.
  4. Represent rational values exactly (Fraction) — keeping exact numerator/denominator fractions prevents floating-point rounding drift and allows direct equality checks against brute-force enumeration.

Why do ad-hoc shortcuts fail? Listing permutations manually, truncating infinite series by hand, or trusting gut intuition on rare-condition screening breaks down immediately. Gut intuition overlooks base rates (how rare a condition is prior to testing) and forgets that conditioning on "Player 1 beats Player 2" filters out long runs of tails.

Watch two examples from our statement in miniature: - Grid rectangles (3 × 4 grid in Example 1): Rather than tallying 1×1, 1×2, ..., 3×4 sizes separately (and risking a missed shape), observe that a 3 × 4 grid is bounded by 4 horizontal lines and 5 vertical lines. Picking 2 horizontal lines (C(4, 2) = 6) and 2 vertical lines (C(5, 2) = 10) immediately produces 6 * 10 = 60 rectangles. - Screening test (2% prevalence, 95% sensitivity, 4% false-positive rate in Example 3): Out of 10,000 people, 200 have the condition (190 test +) and 9,800 do not (392 falsely test +). Out of 190 + 392 = 582 positive results, 190 / 582 = 95/291 ≈ 32.6% truly have the condition.

Complexity

  • Closed-form functions (numbers_from_pairwise_sums, count_rectangles, exact_order_bet_value, horse_option_values, even_stop_probability, expected_flips_given_fewer, reroll_expected_payout, disease_given_positive, second_white_probability, strictly_increasing_probability, average_triple_probability) — O(1) time and O(1) space: Each evaluates a constant number of binomial, permutation, power, or Fraction operations (up to big-integer arithmetic for huge inputs).
  • count_arrangements(word) — O(n) time and O(k) space: Scans the n characters of word once to count k distinct symbols, then computes n! and divides by each symbol's factorial frequency.
  • coupon_collector_cost and box_posterior — O(types) and O(len(boxes)) time, O(1) / O(len(boxes)) space: coupon_collector_cost sums types stage expectations using linearity of expectation (the rule that the expected sum of random waits equals the sum of their individual expectations), and box_posterior evaluates one combinatorial likelihood per container.
  • distinct_color_probabilities — O(∏(min(count_i, draws) + 1) × m) time and O(m) space: Iterates over bounded draw tuples across m categories (3 × 3 × 2 = 18 tuples on [2, 3, 1] with draws = 2) and multiplies m binomial coefficients per valid split.
  • leading_digit_one_probability — O(sides^dice × dice) time and O(dice) space: Visits all sides^dice ordered outcomes (16 for (2, 4), 216 for (3, 6)) and multiplies the dice faces.
  • consistent_role_assignments / true_statement_count — O(r! × r) time and O(r) space: Tests all 4! = 24 permutations of the r = 4 speaker roles across 4 rule checks each (96 checks total).

Edge cases

  • Position 0 in speaker role deduction: Both "jester" and "child" reference the immediately preceding speaker, which does not exist at index 0. Disallowing both at index 0 yields the unique valid assignment ("liar", "jester", "knight", "child") with 3 true claims.
  • Fractional or negative unknowns in numbers_from_pairwise_sums: Odd totals like (1, 1, 1) sum to 3, producing [1/2, 1/2, 1/2] cleanly via Fraction(s1 + s2 + s3, 2); negative sums work identically.
  • Non-terminating rerolls and impossible strict wins: reroll_expected_payout raises ValueError when threshold < 1 (since every face 1..sides would trigger infinite rerolls), and expected_flips_given_fewer raises ValueError when p_heads == 1 (both players tie on toss 1, making A < B have probability 0).
  • Finite vs huge urns in second_white_probability: Without replacement, (N/2 - 1) / (N - 1) equals 4/9 ≈ 0.444 at N = 10, approaching 1/2 asymptotically only as N grows large.

Common mistakes

  • Repeated characters in count_arrangements: Dividing 5! on "LEVEL" by only one 2! instead of 2! * 2!, overcounting by 2× (60 instead of 30).
  • Dividing pairwise sums by 3 instead of 2: In (x + y) + (x + z) + (y + z) = 56, each variable appears twice, so x + y + z = 28, not 56 / 3.
  • Choosing cell rows instead of grid lines in count_rectangles: Computing C(rows, 2) * C(cols, 2) (3 * 6 = 18 on 3 × 4) instead of C(rows + 1, 2) * C(cols + 1, 2) = 60 drops every 1-row or 1-column rectangle.
  • Treating without-replacement draws as independent: Using (2/6)^2 + (3/6)^2 + (1/6)^2 = 7/18 (sampling with replacement) instead of (1 + 3 + 0) / 15 = 4/15 on [2, 3, 1].
  • Guessing 1/2 for even_stop_probability(2): Roll 1 can never terminate the game, whereas roll 2 (an even count!) already halts with probability 1/sides, biasing even counts upward (2/3 for a coin, 3/5 for a 3-sided die).
  • Ignoring conditioning in expected_flips_given_fewer: Returning the unconditional mean 1 / p_heads (3 for p_heads = 1/3) instead of 1 / (1 - (1 - p_heads)^2) = 9/5, forgetting that winning the race rules out long streaks of tails.
  • Confusing sensitivity with posterior probability: Reporting 95% in Example 3 by mistaking P(+ | condition) for P(condition | +) = 95/291 ≈ 32.6%.

Alternative approaches

  • Dynamic programming for larger dice or urn inputs: When dice or len(counts) grows large (say 50 dice or 100 categories), replace explicit Cartesian enumeration with dynamic programming (maintaining a table of exact counts over reachable states one die or one category at a time).
  • Benford's law intuition for leading_digit_one_probability: Benford's law (the observation that products of many independent random variables begin with base-10 digit d with probability near log10(1 + 1/d)) gives log10(2) ≈ 0.3010 for digit 1, remarkably close to 65/216 ≈ 0.3009 on three 6-sided dice!

Follow-up questions

  • In disease_given_positive, if an individual receives two independent positive test results in a row, how do you update the posterior probability cleanly? Work in odds (P(condition) : P(no condition)). On Example 3 (2% prior, 95% sensitivity, 4% false-positive rate), prior odds start at 2 : 98 = 1 : 49, and each independent positive result multiplies the affected side by the likelihood ratio 0.95 / 0.04 = 95/4. One positive result raises odds to 95 : 196 (95/291 ≈ 32.6%), and a second independent positive result multiplies by 95/4 again to 9025 : 784, jumping the posterior probability to 9025 / 9809 ≈ 92.0%!
  • In coupon_collector_cost, how wide is the spread (standard deviation) around the expected spend? Each phase k = 0..types - 1 is an independent geometric random variable (count of packs until a new design of probability p_k = (types - k) / types, with variance (1 - p_k) / p_k^2), so variances add directly across phases. On Example 2 (types = 4, price = 6), pack variances are 0 + 4/9 + 2 + 12 = 130/9 ≈ 14.44, giving a standard deviation of sqrt(130) / 3 ≈ 3.80 packs — or 6 * 3.80 ≈ 22.80 around the expected spend of 50, with over 83% of total variance coming from hunting the final design!
  • In even_stop_probability, what is the expected total number of rolls before two consecutive outcomes match? Roll 1 always sets the initial face, and from roll 2 onward each roll independently matches the previous face with probability 1 / sides. That makes N - 1 a geometric random variable with mean sides, so E[N] = 1 + sides (3 tosses on average for a fair coin, 4 rolls for a 3-sided die, and 7 rolls for a 6-sided die).

Follow-up questions

Similar questions

More Maven Securities interview questions

All 1 Maven Securities questions →