Half-Life Survival, Bidirectional Regression, Door Switching, and Die Coverage

Easy · Statistics & Math · Data Scientist · Onsite

Problem Statement

Implement a collection of analytical and Monte Carlo helpers spanning four classic probability and regression modules:

1. Independent Half-Life Survival

Each particle in a sample has an independent, exponentially distributed lifetime parameterized by half_life > 0 (default 1.0 day), meaning a single particle survives past half_life days with probability 0.5:

  • survival_probability(m: float, half_life: float = 1.0) -> float: Return the probability that a single particle remains intact after m >= 0 days.
  • alive_pmf(n: int, m: float, half_life: float = 1.0) -> List[float]: Starting from n >= 0 independent particles, return a list of length n + 1 where index k (0 <= k <= n) equals P(K = k) for the surviving particle count K at day m.
  • expected_alive(n: int, m: float, half_life: float = 1.0) -> float: Return the expected count E[K] of surviving particles after m days.
  • prob_at_least_one_alive(n: int, m: float, half_life: float = 1.0) -> float: Return P(K >= 1), the probability that one or more of the n particles survive past m days.
  • simulate_decay(n: int, m: float, half_life: float = 1.0, seed: Optional[int] = None) -> List[int]: Draw continuous lifetimes using an isolated random.Random(seed) instance and return a length-n list of 1 (survived past m) and 0 (decayed at or before m) indicators.

2. Bidirectional Linear Regression (Population & Sample OLS)

Suppose y = beta * x + eps, where x and eps are independent zero-mean variables with variances var_x > 0 and var_eps >= 0 (defaulting to beta = 1.0, var_x = 1.0, var_eps = 1.0, such as independent standard normal draws):

  • population_ols_slopes(beta: float = 1.0, var_x: float = 1.0, var_eps: float = 1.0) -> Tuple[float, float]: Return (slope_y_on_x, slope_x_on_y), the population ordinary-least-squares slopes when regressing y on x versus regressing x on y (both population intercepts equal 0.0).
  • ols_fit(xs: List[float], ys: List[float]) -> Tuple[float, float]: Fit ordinary least squares y ~ intercept + slope * x on paired sample lists xs and ys (len >= 2, non-zero sample variance in xs) and return (intercept, slope).

3. Host-Assisted Three-Door Choice

Three closed doors conceal one grand prize and two empty decoys uniformly at random. After a player selects one door uniformly at random, an informed host—who knows where the prize sits—opens a different door guaranteed to hide a decoy, then offers a switch to the remaining closed door:

  • monty_hall_simulation(trials: int, seed: Optional[int] = None) -> Tuple[float, float]: Simulate trials >= 1 independent rounds using random.Random(seed) and return (stay_win_rate, switch_win_rate).

4. Full Face Coverage on a Fair Die

A fair n-sided die (n >= 1) is rolled repeatedly and independently:

  • expected_rolls_all_faces(n: int) -> float: Return the exact expected number of rolls required until all n distinct faces have appeared at least once.

Raise ValueError on invalid domain inputs (half_life <= 0, m < 0, n < 0 in Part 1; mismatched lengths, < 2 points, or zero variance in xs in ols_fit; trials < 1 in Part 3; n < 1 in Part 4).

Examples

Example 1

Input:
  survival_probability(8.0, half_life=1.0)
  expected_alive(80, 8.0, half_life=1.0)
  round(prob_at_least_one_alive(80, 8.0, half_life=1.0), 6)
  alive_pmf(3, 1.0, half_life=1.0)
Output:
  0.00390625
  0.3125
  0.268832
  [0.125, 0.375, 0.375, 0.125]

Explanation: Over 8 half-lives, one particle survives with probability (1/2)^8 = 1/256 = 0.00390625. Across 80 independent particles, E[K] = 80 / 256 = 0.3125 and P(K >= 1) = 1 - (255/256)^80 ≈ 0.268832. With 3 particles after 1 half-life (p = 0.5), Binomial(3, 0.5) produces [1/8, 3/8, 3/8, 1/8].

Example 2

Input:
  population_ols_slopes(beta=1.0, var_x=1.0, var_eps=1.0)
  population_ols_slopes(beta=3.0, var_x=2.0, var_eps=6.0)
  ols_fit([0.0, 2.0, 4.0], [1.0, 4.0, 7.0])
Output:
  (1.0, 0.5)
  (3.0, 0.25)
  (1.0, 1.5)

Explanation: Under unit variances and beta = 1, Cov(x, y) = 1 and Var(y) = 2, giving forward slope 1 / 1 = 1.0 and attenuated reverse slope 1 / 2 = 0.5. When beta = 3, var_x = 2, var_eps = 6, Cov(x, y) = 6 and Var(y) = 18 + 6 = 24, giving (3.0, 0.25). Points on y = 1 + 1.5x fit (1.0, 1.5).

Example 3

Input:
  round(expected_rolls_all_faces(5), 6)
  stay_rate, switch_rate = monty_hall_simulation(20_000, seed=7)
Output:
  11.416667
  stay_rate ≈ 0.333, switch_rate ≈ 0.667  (stay_rate + switch_rate == 1.0)

Explanation: Seeing all 5 faces of a fair 5-sided die takes 5 * (1 + 1/2 + 1/3 + 1/4 + 1/5) = 137 / 12 ≈ 11.416667 rolls on average, while staying versus switching converges to 1/3 and 2/3.

Constraints

  • half_life > 0, m >= 0, 0 <= n <= 1000 for alive_pmf (0 <= n <= 10^5 for simulate_decay).
  • len(xs) == len(ys) >= 2 with positive variance in xs for ols_fit.
  • 1 <= trials <= 10^5 for monty_hall_simulation.
  • 1 <= n <= 10^6 for expected_rolls_all_faces.

Step-by-step walkthrough

  1. Overview: four classic probability pillars in code

    This interview screen bundles four foundational Data Science topics—exponential survival, linear regression in both directions, conditional probability (Monty Hall), and coupon-collector expectations—plus a simulation. Turning each analytical result and simulation into a small, deterministic Python function lets us verify every formula against exact hand calculations and Monte Carlo runs:

    • Part 1 (Radioactive decay): survival_probability, alive_pmf, expected_alive, prob_at_least_one_alive, and simulate_decay.
    • Part 2 (Population OLS): population_ols_slopes for the exact population values and ols_fit to verify them on simulated normal data.
    • Part 3 (Monty Hall): monty_hall_simulation to confirm the 1/3 stay versus 2/3 switch analytical proof.
    • Part 4 (n-sided die): expected_rolls_all_faces.

    Every simulation accepts an optional seed and creates a dedicated random.Random(seed) generator so runs are 100% reproducible without mutating global random state.

  2. Part 1a: From one particle's half-life to the binomial survivor count

    A particle whose lifetime T follows an exponential distribution with rate lambda survives past time t with probability P(T > t) = exp(-lambda * t). Saying the half-life is 1 day means half of a particle's survival probability remains after 1 day:

    P(T > 1) = exp(-lambda * 1) = 1/2   ==>   lambda = ln(2) ≈ 0.6931 per day
    
    After m days, a single particle survives with probability:
      p = P(T > m) = exp(-m * ln(2)) = (1/2)^m
    
    For m = 8 days:
      p = (1/2)^8 = 1 / 256 = 0.00390625
    

    Now start with n = 80 particles that decay independently. After 8 days, each particle acts like an independent weighted coin that lands "alive" with probability p = 1/256 and "decayed" with probability 1 - p = 255/256. The total number of survivors K therefore follows a Binomial distribution:

    K ~ Binomial(n = 80, p = 1/256)
    P(K = k) = C(80, k) * (1/256)^k * (255/256)^(80 - k)   for k = 0, 1, ..., 80
    
    First few probabilities at n = 80, m = 8:
      P(K = 0) = (255/256)^80                     ≈ 0.7312   (73.1% chance zero survive)
      P(K = 1) = 80 * (1/256) * (255/256)^79      ≈ 0.2294   (22.9% chance exactly 1 survives)
      P(K = 2) = 3160 * (1/256)^2 * (255/256)^78  ≈ 0.0355   ( 3.6% chance exactly 2 survive)
      P(K = 3)                                    ≈ 0.0036
    
    from typing import List, Optional, Tuple
    import math
    import random
    
    
    def survival_probability(m: float, half_life: float = 1.0) -> float:
        """Return the probability that one atom is still alive after m days."""
        if half_life <= 0:
            raise ValueError("half_life must be positive")
        if m < 0:
            raise ValueError("m (days) must be non-negative")
        # Every half-life halves the survival chance: P(T > m) = (1/2) ** (m / half_life).
        half_lives_elapsed = m / half_life
        return 0.5 ** half_lives_elapsed
    
    
    def alive_pmf(n: int, m: float, half_life: float = 1.0) -> List[float]:
        """Return [P(K = 0), P(K = 1), ..., P(K = n)] for K surviving atoms after m days."""
        if n < 0:
            raise ValueError("n (atoms) must be non-negative")
        p = survival_probability(m, half_life)
        # pmf[k] stores P(K = k) for K ~ Binomial(n, p), indexed by k from 0 to n.
        pmf = []
        for k in range(n + 1):
            ways_to_choose = math.comb(n, k)
            prob_k_survive = p ** k
            prob_rest_decay = (1.0 - p) ** (n - k)
            pmf.append(ways_to_choose * prob_k_survive * prob_rest_decay)
        return pmf
    
  3. Part 1b: Expected survivors and the complement trick for "at least one"

    For K ~ Binomial(n, p), the expected number of surviving particles is n * p:

    E[K] = n * p = 80 * (1 / 256) = 5 / 16 = 0.3125 particles
    

    To find P(K >= 1) (the probability that at least one particle survives), summing P(K = 1) + P(K = 2) + ... + P(K = 80) takes 80 terms. Instead, flip the question using the complement rule: the opposite of "at least one survives" is "every single particle decayed" (K = 0), which has probability (1 - p)^n:

    P(K >= 1) = 1 - P(K = 0)
              = 1 - (1 - 1/256)^80
              = 1 - (255/256)^80
              ≈ 1 - 0.731168 = 0.268832 ≈ 0.2688
    

    Notice a great sanity check: P(K >= 1) ≈ 0.2688 is strictly smaller than E[K] = 0.3125. Why? Because E[K] occasionally counts 2 or 3 survivors on the same run (0*P(0) + 1*P(1) + 2*P(2) + ...), whereas P(K >= 1) counts all multi-survivor runs only once (1*P(1) + 1*P(2) + ...).

    def expected_alive(n: int, m: float, half_life: float = 1.0) -> float:
        """Return E[K] = n * p, the expected number of atoms still alive after m days."""
        if n < 0:
            raise ValueError("n (atoms) must be non-negative")
        return n * survival_probability(m, half_life)
    
    
    def prob_at_least_one_alive(n: int, m: float, half_life: float = 1.0) -> float:
        """Return P(K >= 1) using the complement rule: 1 - P(all n atoms decayed)."""
        if n < 0:
            raise ValueError("n (atoms) must be non-negative")
        p = survival_probability(m, half_life)
        prob_all_decayed = (1.0 - p) ** n
        return 1.0 - prob_all_decayed
    
  4. Part 1c: Simulate atomic lifetimes in continuous time

    To simulate the physical exponential decay process directly, we draw each atom's continuous lifetime T_i ~ Exponential(rate = ln(2) / half_life) using rng.expovariate(decay_rate) and check whether T_i exceeds m days:

    Day 0                                  Day m
      |--------------------------------------|
      |================X                     |   Atom 0: lifetime <= m  -> 0 (decayed)
      |==========================================X  Atom 1: lifetime > m   -> 1 (alive)
      |=====X                                |   Atom 2: lifetime <= m  -> 0 (decayed)
    

    Drawing one exponential lifetime per atom takes O(n) time regardless of how large m is, and works cleanly for fractional days (m = 0.5) as well as whole days.

    def simulate_decay(n: int, m: float, half_life: float = 1.0, seed: Optional[int] = None) -> List[int]:
        """Simulate n independent atoms over m days; return 1 for alive and 0 for decayed."""
        if n < 0 or m < 0 or half_life <= 0:
            raise ValueError("require n >= 0, m >= 0, and half_life > 0")
        # At m == 0 no time has passed, so every atom is guaranteed alive.
        if m == 0:
            return [1] * n
    
        rng = random.Random(seed)
        # Since P(T > half_life) = exp(-rate * half_life) = 1/2, rate = ln(2) / half_life.
        decay_rate = math.log(2.0) / half_life
        # states[i] is 1 if atom i outlives m days (lifetime > m), else 0.
        states = []
        for _ in range(n):
            lifetime = rng.expovariate(decay_rate)
            if lifetime > m:
                states.append(1)
            else:
                states.append(0)
        return states
    
  5. Part 2: Why regressing x on y does NOT invert regressing y on x

    In simple ordinary least squares (OLS), predicting a target from a predictor chooses intercept a and slope b to minimize the average squared error E[(target - a - b * predictor)^2]. Taking derivatives with respect to a and b and setting them to zero yields the universal population formulas:

    slope     b = Cov(predictor, target) / Var(predictor)
    intercept a = E[target] - b * E[predictor]
    

    Here y = x + eps, where x ~ Normal(0, 1) and eps ~ Normal(0, 1) are independent:

    1. Means: E[x] = 0 and E[y] = E[x] + E[eps] = 0 + 0 = 0, so both intercepts are 0.
    2. Variances: Var(x) = 1, and by independence Var(y) = Var(x) + Var(eps) = 1 + 1 = 2.
    3. Covariance: Cov(x, y) = Cov(x, x + eps) = Cov(x, x) + Cov(x, eps) = Var(x) + 0 = 1.

    Now plug into Cov(predictor, target) / Var(predictor) for each direction:

    Regression A (y on x):  slope = Cov(x, y) / Var(x) = 1 / 1 = 1.0,   intercept = 0.0
    Regression B (x on y):  slope = Cov(y, x) / Var(y) = 1 / 2 = 0.5,   intercept = 0.0
    

    Why is Regression B's slope 0.5 instead of 1 / 1 = 1? Think of y = x + eps as a noisy measurement of x. Because x and eps are independent Normal(0, 1) variables with identical spread, if you observe y = 4, half of that sum on average came from x (2) and half came from noise eps (2), so E[x | y] = 0.5 * y. In statistics, this shrinkage of the slope when the predictor contains noise is called attenuation bias (or regression to the mean). Notice that multiplying the two slopes gives 1.0 * 0.5 = 0.5 = rho^2, the squared correlation between x and y.

    def population_ols_slopes(
        beta: float = 1.0, var_x: float = 1.0, var_eps: float = 1.0
    ) -> Tuple[float, float]:
        """Return (slope of y on x, slope of x on y) for y = beta * x + eps (intercepts are 0)."""
        # Because x and eps are independent: Cov(x, y) = beta * Var(x) and Var(y) = beta^2 * Var(x) + Var(eps).
        cov_xy = beta * var_x
        var_y = (beta ** 2) * var_x + var_eps
        slope_y_on_x = cov_xy / var_x
        # Noise in y inflates Var(y) without changing Cov(x, y), shrinking slope_x_on_y toward 0.
        slope_x_on_y = cov_xy / var_y
        return slope_y_on_x, slope_x_on_y
    
    
    def ols_fit(xs: List[float], ys: List[float]) -> Tuple[float, float]:
        """Fit ordinary least squares y ~ a + b * x on sample data; return (intercept, slope)."""
        n = len(xs)
        if n != len(ys) or n < 2:
            raise ValueError("need two lists of the same length, at least 2 points")
    
        mean_x = sum(xs) / n
        mean_y = sum(ys) / n
        # Accumulate centered cross-product sum((x - mean_x)*(y - mean_y)) and sum((x - mean_x)^2).
        sum_xy = 0.0
        sum_xx = 0.0
        for i in range(n):
            dx = xs[i] - mean_x
            dy = ys[i] - mean_y
            sum_xy += dx * dy
            sum_xx += dx * dx
    
        if sum_xx == 0.0:
            raise ValueError("xs has no variation, so the slope is undefined")
        slope = sum_xy / sum_xx
        intercept = mean_y - slope * mean_x
        return intercept, slope
    
  6. Part 3: Monty Hall via case table and simulation

    Under standard Monty Hall rules, the prize is equally likely behind Doors 1, 2, or 3 (1/3 each), and the host knows where the prize is and must open an unpicked door hiding a goat. Suppose without loss of generality that you initially pick Door 1:

    True prize location (1/3 each)   Door host must open     Stay (Door 1)   Switch (other closed door)
    ------------------------------   ---------------------   -------------   --------------------------
    Door 1 (1/3)                     Door 2 or Door 3        WIN             Lose
    Door 2 (1/3)                     Door 3 (forced!)        Lose            WIN (switches to Door 2)
    Door 3 (1/3)                     Door 2 (forced!)        Lose            WIN (switches to Door 3)
    ---------------------------------------------------------------------------------------------------
    Total win probability                                    1/3             2/3
    

    Why isn't it 50/50 between the two remaining closed doors? Because staying wins if and only if your initial pick was right (1/3), whereas switching wins whenever your initial pick was a goat (2/3)—in that 2/3 case, the host clears away the only other goat for you!

    Bayes' rule confirms the exact same 2/3 if you pick Door 1 and observe the host open Door 3:

    • P(open 3 | prize at 1) = 1/2, P(open 3 | prize at 2) = 1, P(open 3 | prize at 3) = 0.
    • P(open 3) = (1/3)*(1/2) + (1/3)*(1) + (1/3)*(0) = 1/2.
    • P(prize at 2 | open 3) = P(open 3 | prize at 2) * P(prize at 2) / P(open 3) = (1 * 1/3) / (1/2) = 2/3.
    def monty_hall_simulation(trials: int, seed: Optional[int] = None) -> Tuple[float, float]:
        """Simulate `trials` Monty Hall games and return empirical win rates (stay_rate, switch_rate)."""
        if trials < 1:
            raise ValueError("trials must be at least 1")
        rng = random.Random(seed)
        stay_wins = 0
        switch_wins = 0
    
        for _ in range(trials):
            prize_door = rng.randrange(3)
            first_pick = rng.randrange(3)
    
            # Host knows where the prize is and must open a goat door different from first_pick.
            valid_host_doors = []
            for door in range(3):
                if door != first_pick and door != prize_door:
                    valid_host_doors.append(door)
            opened_door = rng.choice(valid_host_doors)
    
            # Switching moves to the single closed door that is neither first_pick nor opened_door.
            switch_door = -1
            for door in range(3):
                if door != first_pick and door != opened_door:
                    switch_door = door
    
            if first_pick == prize_door:
                stay_wins += 1
            if switch_door == prize_door:
                switch_wins += 1
    
        return stay_wins / trials, switch_wins / trials
    
  7. Part 4: Waiting for every die face by splitting into stages

    This is the classic Coupon Collector's Problem. Instead of tracking which specific faces have appeared, break the timeline into n stages based on how many distinct faces (seen = 0, 1, ..., n - 1) have appeared so far:

    Distinct faces seen:   0 ----[R_0]----> 1 ----[R_1]----> 2 ... (n-1) ----[R_{n-1}]----> n
    Unseen faces left:     n                n - 1            n - 2           1
    New-face prob p_i:     n / n = 1        (n - 1) / n      (n - 2) / n     1 / n
    Expected rolls E[R_i]: 1                n / (n - 1)      n / (n - 2)     n
    

    In stage seen, n - seen faces are still unseen out of n equally likely faces, so every roll discovers a brand-new face with probability p = (n - seen) / n. Repeating independent trials with success probability p until the first success is a Geometric(p) random variable whose expected wait is 1 / p = n / (n - seen) rolls.

    By linearity of expectation, total expected rolls equal the sum of the stage expectations:

    E[total rolls] = E[R_0] + E[R_1] + ... + E[R_{n-1}]
                   = n/n + n/(n - 1) + n/(n - 2) + ... + n/1
                   = n * (1 + 1/2 + 1/3 + ... + 1/n)
                   = n * H_n
    

    where H_n is the n-th harmonic number. For a 5-sided die (Example 3), 5 * (1 + 1/2 + 1/3 + 1/4 + 1/5) = 5 + 2.5 + 1.6667 + 1.25 + 1 = 137 / 12 ≈ 11.4167 rolls (and 14.7 rolls for n = 6)—notice the very last unseen face alone takes n rolls on average! For large n, H_n ≈ ln(n) + 0.5772, so E[total rolls] ≈ n * ln(n).

    def expected_rolls_all_faces(n: int) -> float:
        """Return expected rolls of a fair n-sided die to see all n faces: n * (1 + 1/2 + ... + 1/n)."""
        if n < 1:
            raise ValueError("the die needs at least one face")
    
        total_expected_rolls = 0.0
        # Stage `seen`: `seen` distinct faces have appeared, leaving `n - seen` unseen faces.
        for seen in range(n):
            unseen_faces = n - seen
            # New-face probability per roll is unseen_faces / n, so mean geometric wait is n / unseen_faces.
            expected_stage_rolls = n / unseen_faces
            total_expected_rolls += expected_stage_rolls
        return total_expected_rolls
    
  8. Complete solution

    from typing import List, Optional, Tuple
    import math
    import random
    
    
    # ---------- 1) Radioactive decay ----------
    
    def survival_probability(m: float, half_life: float = 1.0) -> float:
        """Return the probability that one atom is still alive after m days."""
        if half_life <= 0:
            raise ValueError("half_life must be positive")
        if m < 0:
            raise ValueError("m (days) must be non-negative")
        # Every half-life halves the survival chance: P(T > m) = (1/2) ** (m / half_life).
        half_lives_elapsed = m / half_life
        return 0.5 ** half_lives_elapsed
    
    
    def alive_pmf(n: int, m: float, half_life: float = 1.0) -> List[float]:
        """Return [P(K = 0), P(K = 1), ..., P(K = n)] for K surviving atoms after m days."""
        if n < 0:
            raise ValueError("n (atoms) must be non-negative")
        p = survival_probability(m, half_life)
        # pmf[k] stores P(K = k) for K ~ Binomial(n, p), indexed by k from 0 to n.
        pmf = []
        for k in range(n + 1):
            ways_to_choose = math.comb(n, k)
            prob_k_survive = p ** k
            prob_rest_decay = (1.0 - p) ** (n - k)
            pmf.append(ways_to_choose * prob_k_survive * prob_rest_decay)
        return pmf
    
    
    def expected_alive(n: int, m: float, half_life: float = 1.0) -> float:
        """Return E[K] = n * p, the expected number of atoms still alive after m days."""
        if n < 0:
            raise ValueError("n (atoms) must be non-negative")
        return n * survival_probability(m, half_life)
    
    
    def prob_at_least_one_alive(n: int, m: float, half_life: float = 1.0) -> float:
        """Return P(K >= 1) using the complement rule: 1 - P(all n atoms decayed)."""
        if n < 0:
            raise ValueError("n (atoms) must be non-negative")
        p = survival_probability(m, half_life)
        prob_all_decayed = (1.0 - p) ** n
        return 1.0 - prob_all_decayed
    
    
    def simulate_decay(n: int, m: float, half_life: float = 1.0, seed: Optional[int] = None) -> List[int]:
        """Simulate n independent atoms over m days; return 1 for alive and 0 for decayed."""
        if n < 0 or m < 0 or half_life <= 0:
            raise ValueError("require n >= 0, m >= 0, and half_life > 0")
        # At m == 0 no time has passed, so every atom is guaranteed alive.
        if m == 0:
            return [1] * n
    
        rng = random.Random(seed)
        # Since P(T > half_life) = exp(-rate * half_life) = 1/2, rate = ln(2) / half_life.
        decay_rate = math.log(2.0) / half_life
        # states[i] is 1 if atom i outlives m days (lifetime > m), else 0.
        states = []
        for _ in range(n):
            lifetime = rng.expovariate(decay_rate)
            if lifetime > m:
                states.append(1)
            else:
                states.append(0)
        return states
    
    
    # ---------- 2) Population OLS ----------
    
    def population_ols_slopes(
        beta: float = 1.0, var_x: float = 1.0, var_eps: float = 1.0
    ) -> Tuple[float, float]:
        """Return (slope of y on x, slope of x on y) for y = beta * x + eps (intercepts are 0)."""
        # Because x and eps are independent: Cov(x, y) = beta * Var(x) and Var(y) = beta^2 * Var(x) + Var(eps).
        cov_xy = beta * var_x
        var_y = (beta ** 2) * var_x + var_eps
        slope_y_on_x = cov_xy / var_x
        # Noise in y inflates Var(y) without changing Cov(x, y), shrinking slope_x_on_y toward 0.
        slope_x_on_y = cov_xy / var_y
        return slope_y_on_x, slope_x_on_y
    
    
    def ols_fit(xs: List[float], ys: List[float]) -> Tuple[float, float]:
        """Fit ordinary least squares y ~ a + b * x on sample data; return (intercept, slope)."""
        n = len(xs)
        if n != len(ys) or n < 2:
            raise ValueError("need two lists of the same length, at least 2 points")
    
        mean_x = sum(xs) / n
        mean_y = sum(ys) / n
        # Accumulate centered cross-product sum((x - mean_x)*(y - mean_y)) and sum((x - mean_x)^2).
        sum_xy = 0.0
        sum_xx = 0.0
        for i in range(n):
            dx = xs[i] - mean_x
            dy = ys[i] - mean_y
            sum_xy += dx * dy
            sum_xx += dx * dx
    
        if sum_xx == 0.0:
            raise ValueError("xs has no variation, so the slope is undefined")
        slope = sum_xy / sum_xx
        intercept = mean_y - slope * mean_x
        return intercept, slope
    
    
    # ---------- 3) Monty Hall ----------
    
    def monty_hall_simulation(trials: int, seed: Optional[int] = None) -> Tuple[float, float]:
        """Simulate `trials` Monty Hall games and return empirical win rates (stay_rate, switch_rate)."""
        if trials < 1:
            raise ValueError("trials must be at least 1")
        rng = random.Random(seed)
        stay_wins = 0
        switch_wins = 0
    
        for _ in range(trials):
            prize_door = rng.randrange(3)
            first_pick = rng.randrange(3)
    
            # Host knows where the prize is and must open a goat door different from first_pick.
            valid_host_doors = []
            for door in range(3):
                if door != first_pick and door != prize_door:
                    valid_host_doors.append(door)
            opened_door = rng.choice(valid_host_doors)
    
            # Switching moves to the single closed door that is neither first_pick nor opened_door.
            switch_door = -1
            for door in range(3):
                if door != first_pick and door != opened_door:
                    switch_door = door
    
            if first_pick == prize_door:
                stay_wins += 1
            if switch_door == prize_door:
                switch_wins += 1
    
        return stay_wins / trials, switch_wins / trials
    
    
    # ---------- 4) Seeing every face of an n-sided die ----------
    
    def expected_rolls_all_faces(n: int) -> float:
        """Return expected rolls of a fair n-sided die to see all n faces: n * (1 + 1/2 + ... + 1/n)."""
        if n < 1:
            raise ValueError("the die needs at least one face")
    
        total_expected_rolls = 0.0
        # Stage `seen`: `seen` distinct faces have appeared, leaving `n - seen` unseen faces.
        for seen in range(n):
            unseen_faces = n - seen
            # New-face probability per roll is unseen_faces / n, so mean geometric wait is n / unseen_faces.
            expected_stage_rolls = n / unseen_faces
            total_expected_rolls += expected_stage_rolls
        return total_expected_rolls
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Each of these four classic probability questions looks tricky until you break a big, tangled event into simple, independent building blocks. Think of it like counting bricks instead of weighing a whole wall at once:

  • Half-life survival turns 80 particles over 8 days into 80 independent weighted coin flips, because an exponential distribution (a continuous waiting-time distribution with a constant hazard rate) halves its survival probability every half-life.
  • Population OLS (ordinary least squares, the straight line minimizing average squared prediction error) sets the slope to Cov(predictor, target) / Var(predictor), so adding noise to the predictor inflates the denominator and shrinks the reverse slope.
  • Three-door switching hinges on conditional probability (updating probabilities using how information was generated): because the host knows where the prize sits and never opens it, switching wins every time your first guess was an empty decoy.
  • Rolling all n die faces splits into n back-to-back geometric waits (the number of independent trials needed until the next success), summed effortlessly by linearity of expectation (the rule that the expected value of a sum always equals the sum of the expected values).

Naive intuition stumbles on all four. People often confuse E[survivors] = n * p with P(at least one survivor), invert an OLS slope b as 1 / b as if there were no noise, assume two closed doors must be 50/50, or guess it takes n rolls to see n die faces because they forget that duplicate faces pile up near the end.

Walk through tiny concrete numbers to see every mechanism click:

  1. 3 particles after 1 day (half-life = 1 day): Each particle survives with p = 1/2. K ~ Binomial(3, 1/2) gives [0.125, 0.375, 0.375, 0.125], E[K] = 3 * 0.5 = 1.5, and P(K >= 1) = 1 - (1 - 0.5)^3 = 0.875. (At n = 80, m = 8, p = 1/256, E[K] = 0.3125, and P(K >= 1) = 1 - (255/256)^80 ≈ 0.2688.)
  2. OLS on y = x + eps: Suppose x = 1 and eps = 1, or x = 1 and eps = -1. On average y tracks x 1-for-1 (slope = 1), whereas seeing a noisy sum y = 2 splits credit evenly between x and eps, giving E[x | y] = 0.5 * y (slope = 0.5, intercept 0).
  3. 5-sided die (n = 5): Stage waits average 5/5 = 1, 5/4 = 1.25, 5/3 ≈ 1.6667, 5/2 = 2.5, and 5/1 = 5 rolls—summing to 137 / 12 ≈ 11.4167 rolls total.

Complexity

  • Closed-form functions (survival_probability, expected_alive, prob_at_least_one_alive, population_ols_slopes) — Time O(1), Space O(1): Each performs a fixed handful of floating-point operations with no loops or collections.
  • alive_pmf — Time O(n) arithmetic steps, Space O(n): We loop k from 0 to n (n + 1 iterations) to build the output list of length n + 1 (math.comb(n, k) is negligible for moderate n like 100).
  • simulate_decay — Time O(n), Space O(n): We draw exactly one exponential lifetime per atom and store n 0/1 flags, avoiding an O(n * m) day-by-day loop.
  • ols_fit — Time O(n), Space O(1): Two linear passes over the n data points (one for sample means, one for centered sums of squares and cross-products) using only scalar accumulators.
  • monty_hall_simulation — Time O(trials), Space O(1): Each simulated game inspects just 3 doors and updates two integer counters.
  • expected_rolls_all_faces — Time O(n), Space O(1): One loop of n terms accumulates n / (n - seen) into a single float.

Edge cases

  • Zero elapsed time (m = 0): Every atom survives (p = 1.0), alive_pmf(n, 0) puts probability 1.0 at index n, expected_alive returns n, and simulate_decay returns [1] * n immediately.
  • Zero atoms (n = 0): expected_alive(0, m) and prob_at_least_one_alive(0, m) both return 0.0, alive_pmf(0, m) returns [1.0], and simulate_decay(0, m) returns [].
  • Large n overflow in alive_pmf: For n >= 1030, math.comb(n, k) exceeds the maximum 64-bit float (~1.8e308) when converted to float. In large-n settings, compute log-probabilities using math.lgamma and exponentiate at the end.
  • Catastrophic cancellation for tiny p: When m >= 54 half-lives, p = 2^(-m) is smaller than machine epsilon (2^(-53)), so 1.0 - p rounds to 1.0 and 1.0 - (1.0 - p)**n underflows to 0.0. Using -math.expm1(n * math.log1p(-p)) preserves full precision for tiny p.
  • Zero noise in OLS (var_eps = 0): Both regressions lie on the exact noiseless line y = beta * x, giving slopes (beta, 1 / beta).
  • Constant xs in ols_fit: When all x_i are identical (sum_xx == 0), a vertical cloud has no well-defined slope, so ols_fit raises ValueError.
  • 1-sided die (n = 1): expected_rolls_all_faces(1) returns 1.0 roll.

Common mistakes

  • Treating the half-life as the average lifetime: Half-life (1 day) is the median of the exponential distribution, whereas the mean lifetime is 1 / lambda = 1 / ln(2) ≈ 1.443 days. Passing rate = 1.0 instead of math.log(2) / half_life to expovariate simulates the wrong decay rate.
  • Confusing E[K] with P(K >= 1): Writing n * p = 0.3125 for P(at least one alive) double-counts outcomes with 2 or more survivors (and can even exceed 1.0 when n * p > 1!). Always use 1 - (1 - p)^n.
  • Inverting the forward OLS slope (1 / b) for reverse regression: Because y contains measurement noise eps, regressing x on y suffers attenuation bias (shrinkage of the slope toward 0 by the signal-to-total-variance factor Var(x) / Var(y) = 1/2).
  • Simulating a "clueless host": Having the host open a random unpicked door and discarding runs where the prize appears changes the conditional event and yields 1/2 instead of 2/3. Under standard rules, the host never opens the prize door.
  • Off-by-one range in the harmonic sum: Summing 1 / i up to n - 1 (range(1, n)) misses the 1 / n term! Over seen in range(n), n - seen cleanly visits n, n - 1, ..., 1.

Follow-up questions

  • Starting with 80 independent particles of half-life 1 day, what is the expected time until the final surviving particle decays? This is the continuous cousin of the n-sided die! Because the memoryless property (surviving particles reset as good as new at every instant) implies that k surviving particles have combined decay rate k * lambda, the wait from 80 down to 79 particles averages 1 / (80 * lambda), down to 78 averages 1 / (79 * lambda), and the very last particle averages 1 / (1 * lambda). Summing gives H_80 / ln(2) ≈ 4.9655 / 0.6931 ≈ 7.16 days, where harmonic number H_80 = 1 + 1/2 + ... + 1/80.
  • In an n-door version of the game, how does the switching win probability compare when the host opens n - 2 losing doors versus just one losing door? Staying always wins with probability 1 / n. If the host opens n - 2 losing doors (leaving only one other closed door), all (n - 1) / n remaining probability lands on that single door, so switching wins (n - 1) / n (for 100 doors, 99%!). If the host opens only one losing door, that (n - 1) / n mass splits evenly across the n - 2 other closed doors, so switching to one of them wins ((n - 1) / n) * (1 / (n - 2))—for 4 doors that is 3/8 = 37.5%, still beating 1/4 = 25%!
  • What is the variance of the roll count required to observe every face of a fair n-sided die? Because each stage's wait R_i only counts rolls until the next unseen face (without caring which unseen face appeared), the random variables R_0, R_1, ..., R_{n-1} are independent with success probabilities p_i = (n - i) / n. A geometric wait has variance (1 - p_i) / p_i^2, so summing across stages gives Var(R) = n^2 * (1 + 1/4 + ... + 1/n^2) - n * H_n; for a 6-sided die this is 36 * 1.4914 - 14.7 ≈ 38.99 (standard deviation ≈ 6.24 rolls).

Follow-up questions

Similar questions

More Upstart interview questions

All 51 Upstart questions →