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 afterm >= 0days.alive_pmf(n: int, m: float, half_life: float = 1.0) -> List[float]: Starting fromn >= 0independent particles, return a list of lengthn + 1where indexk(0 <= k <= n) equalsP(K = k)for the surviving particle countKat daym.expected_alive(n: int, m: float, half_life: float = 1.0) -> float: Return the expected countE[K]of surviving particles aftermdays.prob_at_least_one_alive(n: int, m: float, half_life: float = 1.0) -> float: ReturnP(K >= 1), the probability that one or more of thenparticles survive pastmdays.simulate_decay(n: int, m: float, half_life: float = 1.0, seed: Optional[int] = None) -> List[int]: Draw continuous lifetimes using an isolatedrandom.Random(seed)instance and return a length-nlist of1(survived pastm) and0(decayed at or beforem) 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 regressingyonxversus regressingxony(both population intercepts equal0.0).ols_fit(xs: List[float], ys: List[float]) -> Tuple[float, float]: Fit ordinary least squaresy ~ intercept + slope * xon paired sample listsxsandys(len >= 2, non-zero sample variance inxs) 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]: Simulatetrials >= 1independent rounds usingrandom.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 allndistinct 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 <= 1000foralive_pmf(0 <= n <= 10^5forsimulate_decay).len(xs) == len(ys) >= 2with positive variance inxsforols_fit.1 <= trials <= 10^5formonty_hall_simulation.1 <= n <= 10^6forexpected_rolls_all_faces.
Step-by-step walkthrough
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, andsimulate_decay. - Part 2 (Population OLS):
population_ols_slopesfor the exact population values andols_fitto verify them on simulated normal data. - Part 3 (Monty Hall):
monty_hall_simulationto confirm the1/3stay versus2/3switch analytical proof. - Part 4 (n-sided die):
expected_rolls_all_faces.
Every simulation accepts an optional
seedand creates a dedicatedrandom.Random(seed)generator so runs are 100% reproducible without mutating global random state.- Part 1 (Radioactive decay):
Part 1a: From one particle's half-life to the binomial survivor count
A particle whose lifetime
Tfollows an exponential distribution with ratelambdasurvives past timetwith probabilityP(T > t) = exp(-lambda * t). Saying the half-life is1day means half of a particle's survival probability remains after1day: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.00390625Now start with
n = 80particles that decay independently. After8days, each particle acts like an independent weighted coin that lands "alive" with probabilityp = 1/256and "decayed" with probability1 - p = 255/256. The total number of survivorsKtherefore 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.0036from 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 pmfPart 1b: Expected survivors and the complement trick for "at least one"
For
K ~ Binomial(n, p), the expected number of surviving particles isn * p:E[K] = n * p = 80 * (1 / 256) = 5 / 16 = 0.3125 particlesTo find
P(K >= 1)(the probability that at least one particle survives), summingP(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.2688Notice a great sanity check:
P(K >= 1) ≈ 0.2688is strictly smaller thanE[K] = 0.3125. Why? BecauseE[K]occasionally counts2or3survivors on the same run (0*P(0) + 1*P(1) + 2*P(2) + ...), whereasP(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_decayedPart 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)usingrng.expovariate(decay_rate)and check whetherT_iexceedsmdays: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 largemis, 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 statesPart 2: Why regressing x on y does NOT invert regressing y on x
In simple ordinary least squares (OLS), predicting a
targetfrom apredictorchooses interceptaand slopebto minimize the average squared errorE[(target - a - b * predictor)^2]. Taking derivatives with respect toaandband 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, wherex ~ Normal(0, 1)andeps ~ Normal(0, 1)are independent:- Means:
E[x] = 0andE[y] = E[x] + E[eps] = 0 + 0 = 0, so both intercepts are0. - Variances:
Var(x) = 1, and by independenceVar(y) = Var(x) + Var(eps) = 1 + 1 = 2. - 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.0Why is Regression B's slope
0.5instead of1 / 1 = 1? Think ofy = x + epsas a noisy measurement ofx. Becausexandepsare independentNormal(0, 1)variables with identical spread, if you observey = 4, half of that sum on average came fromx(2) and half came from noiseeps(2), soE[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 gives1.0 * 0.5 = 0.5 = rho^2, the squared correlation betweenxandy.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- Means:
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/3each), 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/3Why 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 that2/3case, the host clears away the only other goat for you!Bayes' rule confirms the exact same
2/3if 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 / trialsPart 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
nstages 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) nIn stage
seen,n - seenfaces are still unseen out ofnequally likely faces, so every roll discovers a brand-new face with probabilityp = (n - seen) / n. Repeating independent trials with success probabilitypuntil the first success is a Geometric(p) random variable whose expected wait is1 / 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_nwhere
H_nis then-th harmonic number. For a5-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.4167rolls (and14.7rolls forn = 6)—notice the very last unseen face alone takesnrolls on average! For largen,H_n ≈ ln(n) + 0.5772, soE[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_rollsComplete 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
80particles over8days into80independent 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
ndie faces splits intonback-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:
- 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, andP(K >= 1) = 1 - (1 - 0.5)^3 = 0.875. (Atn = 80, m = 8,p = 1/256,E[K] = 0.3125, andP(K >= 1) = 1 - (255/256)^80 ≈ 0.2688.) - OLS on
y = x + eps: Supposex = 1andeps = 1, orx = 1andeps = -1. On averageytracksx1-for-1 (slope = 1), whereas seeing a noisy sumy = 2splits credit evenly betweenxandeps, givingE[x | y] = 0.5 * y(slope = 0.5, intercept0). - 5-sided die (
n = 5): Stage waits average5/5 = 1,5/4 = 1.25,5/3 ≈ 1.6667,5/2 = 2.5, and5/1 = 5rolls—summing to137 / 12 ≈ 11.4167rolls total.
Complexity
- Closed-form functions (
survival_probability,expected_alive,prob_at_least_one_alive,population_ols_slopes) — TimeO(1), SpaceO(1): Each performs a fixed handful of floating-point operations with no loops or collections. alive_pmf— TimeO(n)arithmetic steps, SpaceO(n): We loopkfrom0ton(n + 1iterations) to build the output list of lengthn + 1(math.comb(n, k)is negligible for moderatenlike100).simulate_decay— TimeO(n), SpaceO(n): We draw exactly one exponential lifetime per atom and storen0/1flags, avoiding anO(n * m)day-by-day loop.ols_fit— TimeO(n), SpaceO(1): Two linear passes over thendata points (one for sample means, one for centered sums of squares and cross-products) using only scalar accumulators.monty_hall_simulation— TimeO(trials), SpaceO(1): Each simulated game inspects just3doors and updates two integer counters.expected_rolls_all_faces— TimeO(n), SpaceO(1): One loop ofnterms accumulatesn / (n - seen)into a single float.
Edge cases
- Zero elapsed time (
m = 0): Every atom survives (p = 1.0),alive_pmf(n, 0)puts probability1.0at indexn,expected_alivereturnsn, andsimulate_decayreturns[1] * nimmediately. - Zero atoms (
n = 0):expected_alive(0, m)andprob_at_least_one_alive(0, m)both return0.0,alive_pmf(0, m)returns[1.0], andsimulate_decay(0, m)returns[]. - Large
noverflow inalive_pmf: Forn >= 1030,math.comb(n, k)exceeds the maximum 64-bit float (~1.8e308) when converted tofloat. In large-nsettings, compute log-probabilities usingmath.lgammaand exponentiate at the end. - Catastrophic cancellation for tiny
p: Whenm >= 54half-lives,p = 2^(-m)is smaller than machine epsilon (2^(-53)), so1.0 - prounds to1.0and1.0 - (1.0 - p)**nunderflows to0.0. Using-math.expm1(n * math.log1p(-p))preserves full precision for tinyp. - Zero noise in OLS (
var_eps = 0): Both regressions lie on the exact noiseless liney = beta * x, giving slopes(beta, 1 / beta). - Constant
xsinols_fit: When allx_iare identical (sum_xx == 0), a vertical cloud has no well-defined slope, sools_fitraisesValueError. - 1-sided die (
n = 1):expected_rolls_all_faces(1)returns1.0roll.
Common mistakes
- Treating the half-life as the average lifetime: Half-life (
1day) is the median of the exponential distribution, whereas the mean lifetime is1 / lambda = 1 / ln(2) ≈ 1.443days. Passingrate = 1.0instead ofmath.log(2) / half_lifetoexpovariatesimulates the wrong decay rate. - Confusing
E[K]withP(K >= 1): Writingn * p = 0.3125forP(at least one alive)double-counts outcomes with2or more survivors (and can even exceed1.0whenn * p > 1!). Always use1 - (1 - p)^n. - Inverting the forward OLS slope (
1 / b) for reverse regression: Becauseycontains measurement noiseeps, regressingxonysuffers attenuation bias (shrinkage of the slope toward0by the signal-to-total-variance factorVar(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/2instead of2/3. Under standard rules, the host never opens the prize door. - Off-by-one range in the harmonic sum: Summing
1 / iup ton - 1(range(1, n)) misses the1 / nterm! Overseen in range(n),n - seencleanly visitsn, 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 thatksurviving particles have combined decay ratek * lambda, the wait from80down to79particles averages1 / (80 * lambda), down to78averages1 / (79 * lambda), and the very last particle averages1 / (1 * lambda). Summing givesH_80 / ln(2) ≈ 4.9655 / 0.6931 ≈ 7.16days, where harmonic numberH_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 opensn - 2losing doors (leaving only one other closed door), all(n - 1) / nremaining probability lands on that single door, so switching wins(n - 1) / n(for100doors,99%!). If the host opens only one losing door, that(n - 1) / nmass splits evenly across then - 2other closed doors, so switching to one of them wins((n - 1) / n) * (1 / (n - 2))—for4doors that is3/8 = 37.5%, still beating1/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_ionly counts rolls until the next unseen face (without caring which unseen face appeared), the random variablesR_0, R_1, ..., R_{n-1}are independent with success probabilitiesp_i = (n - i) / n. A geometric wait has variance(1 - p_i) / p_i^2, so summing across stages givesVar(R) = n^2 * (1 + 1/4 + ... + 1/n^2) - n * H_n; for a6-sided die this is36 * 1.4914 - 14.7 ≈ 38.99(standard deviation≈ 6.24rolls).
Follow-up questions
- Starting with 80 independent particles of half-life 1 day, what is the expected time until the final surviving particle decays?
- 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?
- What is the variance of the roll count required to observe every face of a fair n-sided die?
Similar questions
- Stopping-Time Analysis for Competing Two-Toss Coin Patterns
- Exact Binomial Coin-Flip Probability
- Expected Runs in Independent Coin Flips
- Exact Survivor Probability Under Exponential Decay
- Optimal Sensor Fusion and 2D Random-Walk Coordinate Correlations
- Debiasing Household Size Probabilities From Child Surveys
More Upstart interview questions
- Smallest Axis-Aligned Enclosing Box Easy
- Observational Causal Lift and Multi-Arm Launch Forecasting Easy
- Multiply Recipe Ingredient Amounts Easy Pro
- Probability, Bayes, and Regression Metrics Medium Pro
- Optimal Sensor Fusion and 2D Random-Walk Coordinate Correlations Easy Pro
- Dining Hall Revenue With FIFO Waitlist Medium Pro
- Debiasing Household Size Probabilities From Child Surveys Easy Pro
- Alphabetical Word Frequency Counts Medium Pro
- Reconstruct Scrambled Sentences Using Endpoint and Anagram Rules Medium Pro
- Marketing Funnel Analysis and Incremental Spend Allocation Hard Pro