Calendar Collision Thresholds and Circular Minimum Spacings
Hard · Statistics & Math · Quantitative Researcher · Onsite
Problem Statement
Implement birthday_collision_and_spacing(n, d, days=365) to compute five analytical and approximate quantities across two uniform random-placement models, returning them in a dictionary with these exact keys:
- Discrete calendar collisions (
daysequally likely days, independent uniform assignment):"minimum_people": The smallest integer group sizem >= 1for which the probability that at least two individuals land on the same day is strictly greater than0.5."approximate_minimum_people": The continuous approximationsqrt(2 * days * ln(2))obtained by replacing1 - k / dayswithe^(-k / days)andm * (m - 1)withm^2.
- Continuous circular spacings (
npoints dropped independently and uniformly around a closed loop of perimeter1): LetXdenote the shortest arc distance along the perimeter-1circle separating any two of thenpoints."expected_minimum_spacing": The exact expected valueE[X]of the minimum circular gap."probability_closest_distance_greater_than_d": The exact survival probabilityP(X > d)on the perimeter-1circle (returning1.0wheneverd <= 0and0.0whenevern * d >= 1)."poisson_approximation": The small-dPoisson-process estimatee^(-n^2 * d)obtained by modeling thencircular gaps as independentExponential(n)spacings whend > 0(and1.0whend <= 0).
Examples
Example 1
Input: n = 200, d = 0.000005, days = 365
Output:
{
"minimum_people": 23,
"approximate_minimum_people": 22.49438689559598,
"expected_minimum_spacing": 2.5e-05,
"probability_closest_distance_greater_than_d": 0.819468297776412,
"poisson_approximation": 0.8187307530779818
}
On a 365-day calendar, 23 people push the match probability past 0.5 (sqrt(730 * ln(2)) ≈ 22.4944). For n = 200 circular points, E[X] = 1 / 200^2 = 0.000025, and at d = 0.000005 (n * d = 0.001), exact (1 - 0.001)^199 ≈ 0.819468 closely matches Poisson e^(-0.2) ≈ 0.818731.
Example 2
Input: n = 100, d = 0.002, days = 400
Output:
{
"minimum_people": 24,
"approximate_minimum_people": 23.548200450309494,
"expected_minimum_spacing": 0.0001,
"probability_closest_distance_greater_than_d": 2.5462949704181216e-10,
"poisson_approximation": 2.061153622438558e-09
}
A 400-day calendar requires 24 people (sqrt(800 * ln(2)) ≈ 23.5482). With n = 100 and d = 0.002, the 100 buffers consume n * d = 0.2 of the loop, making exact 0.8^99 ≈ 2.55e-10 nearly an order of magnitude smaller than e^(-20) ≈ 2.06e-9.
Example 3
Input: n = 4, d = 0.15, days = 30
Output:
{
"minimum_people": 7,
"approximate_minimum_people": 6.44894028764391,
"expected_minimum_spacing": 0.0625,
"probability_closest_distance_greater_than_d": 0.064,
"poisson_approximation": 0.09071795328941251
}
On a 30-day calendar, 6 distinct picks occur with probability 0.5864 and 7 with 0.4691 < 0.5, so "minimum_people" is 7. Around the loop, 4 points have E[X] = 1 / 16 = 0.0625 and exact P(X > 0.15) = (1 - 0.6)^3 = 0.064.
Constraints
1 <= days <= 10^72 <= n <= 10^6dis a floating-point number (may be<= 0, in(0, 1 / n), or>= 1 / n).- All birthdays and circular positions are mutually independent and uniformly distributed.
Step-by-step walkthrough
Understand all five outputs
The function computes five quantities across a discrete calendar model and a continuous perimeter-
1circle model, returning them in one dictionary:Output key What it measures Inputs used minimum_peopleSmallest integer group size mwhereP(at least two share a day) > 0.5daysapproximate_minimum_peopleContinuous estimate of that threshold via e^(-x) ≈ 1 - xdaysexpected_minimum_spacingE[X], the expected shortest arc gapXamongnuniform points on a perimeter-1circlenprobability_closest_distance_greater_than_dExact survival probability P(X > d)on the perimeter-1circlen,dpoisson_approximationSmall- dPoisson-process estimate ofP(X > d)n,dKeep the wrap-around geometry in mind: because the year forms a closed loop of perimeter
1(where1.0wraps directly back to0.0),npoints partition the circle intonidentically behaved neighbouring arcs rather than leaving two unconnected boundary segments at the ends.Discrete collision threshold (exact): multiply collision-free probabilities
Counting "at least two people match" directly is messy because two people might match, three might match, or two separate pairs might collide at once. Flipping to the complementary event — every single person lands on a distinct day — turns the problem into one step-by-step product.
Imagine people entering an empty room one by one under a
days-day calendar:Person 1 enters: 0 days occupied -> days / days chance of no match Person 2 enters: 1 day occupied -> (days - 1) / days chance of avoiding Person 1 Person 3 enters: 2 days occupied -> (days - 2) / days chance of avoiding both ... Person k enters: k - 1 occupied -> (days - (k - 1)) / daysBecause each newcomer's day is independent of previous picks, we multiply those fractions one person at a time. Requiring
P(shared birthday) > 0.5is identical to requiringP(all distinct) < 0.5.Watch
<versus<=carefully: keep loopingwhile prob_all_distinct >= 0.5. On a 2-day calendar (days = 2), 2 people giveP(all distinct) = 1/2, soP(shared) = 1/2, which is not strictly above0.5; the loop properly advances to a 3rd person.def minimum_people_for_shared_birthday(days: int) -> int: """Return the smallest group size n where P(at least two share a birthday) > 0.5.""" # prob_all_distinct tracks P(all people so far have different birthdays), starting at 1.0 for 0 people. prob_all_distinct = 1.0 people = 0 # P(shared birthday) > 0.5 is equivalent to P(all distinct) < 0.5. # Use >= 0.5 (not > 0.5) so an exact 0.5 tie (which happens when days == 2, people == 2) keeps adding a person. while prob_all_distinct >= 0.5: people += 1 # Person `people` must land on one of the `days - (people - 1)` days not yet taken. available_days = days - (people - 1) prob_all_distinct *= available_days / days return peopleDiscrete collision threshold (approximation): convert the product via e^(-x)
To see why the threshold scales with the square root of
days, writeD = daysand express each factor(D - k) / Das1 - k / Dfork = 0, 1, ..., m - 1.When
xis small, the first-order Taylor expansion (approximatinge^(-x)near0by its tangent line) gives1 - x ≈ e^(-x). Substitutinge^(-k / D)for each factor turns multiplication into addition in the exponent:P(all m distinct) = (1 - 0/D) * (1 - 1/D) * (1 - 2/D) * ... * (1 - (m - 1)/D) ≈ e^(-0/D) * e^(-1/D) * e^(-2/D) * ... * e^(-(m - 1)/D) = e^(-(0 + 1 + 2 + ... + (m - 1)) / D)Using
0 + 1 + ... + (m - 1) = m * (m - 1) / 2and simplifyingm * (m - 1) ≈ m^2:P(all m distinct) ≈ e^(-m * (m - 1) / (2 * D)) ≈ e^(-m^2 / (2 * D))Setting this equal to
1/2and solving form:e^(-m^2 / (2 * D)) = 1/2 -m^2 / (2 * D) = ln(1/2) = -ln(2) (take natural logarithms) m^2 = 2 * D * ln(2) (multiply both sides by -2 * D) m = sqrt(2 * D * ln(2))For
D = 365,sqrt(2 * 365 * ln(2)) ≈ 22.4944, just below the exact integer23; forD = 400,sqrt(800 * ln(2)) ≈ 23.5482, just below24.Exact circular survival probability P(X > d)
Deriving
P(X > d)beforeE[X]gives us the expected spacing almost immediately.Drop
npoints uniformly around a circle of perimeter1. By rotational symmetry, rotate the circle so Point 1 sits at0(which wraps around and meets1). In clockwise order, thenpoints divide the circle intonconsecutive arc lengthsg_1, g_2, ..., g_nsumming to1:Unwrapped circle of perimeter 1 (0 and 1 are the same point, Point 1): 0=P1 P(2) P(3) P(4) 1=P1 |-----------|---------------|------------------|------------| g_1 g_2 g_3 g_4 (g_1 + ... + g_4 = 1)The two closest points must be adjacent along the circle, so
X = min(g_1, ..., g_n). RequiringX > dmeans every single one of thenarcs exceedsd.Think of each arc
g_i = d + h_ias reserving a mandatory buffer of lengthdplus positive slackh_i > 0: - Ifd <= 0, every arc between distinct continuous points is automatically> d, soP(X > d) = 1.0. - Ifn * d >= 1, thenbuffers alone consume at least the entire perimeter1, leaving zero room for positive slack, soP(X > d) = 0.0. - When0 < d < 1 / n, cutting out thenbuffers of lengthdleaves1 - n * dof free perimeter shared across then - 1remaining point coordinates: - Forn = 2(1 free coordinate): the second point must fall inside[d, 1 - d], an interval of length(1 - 2*d)^1. - Forn = 3(2 free coordinates): scaling down the valid 2D simplex by1 - 3*dalong both axes scales its area to(1 - 3*d)^2. - In general, scaling an(n - 1)-dimensional coordinate region by1 - n * dalong every axis multiplies its volume — and probability — by(1 - n * d)^(n - 1).def prob_closest_pair_farther_than(n: int, d: float) -> float: """Return exact P(minimum circular distance X among n uniform points on a length-1 circle > d).""" # Distances between distinct random points are strictly positive, so X > d is certain when d <= 0. if d <= 0.0: return 1.0 # All n adjacent arcs around the circle must each exceed d, requiring n * d < 1 total buffer length. if n * d >= 1.0: return 0.0 # Removing n mandatory buffers of length d leaves (1 - n * d) of slack across (n - 1) free coordinates. remaining_circle_fraction = 1.0 - n * d return remaining_circle_fraction ** (n - 1)Integrate the survival curve to obtain E[X] = 1 / n^2
For any non-negative random variable
X, the tail-integral identity states thatE[X]equals the area underP(X > t)fort >= 0. SinceP(X > t) = 0oncet >= 1 / n, we integrate fromt = 0tot = 1 / n:E[X] = integral from t = 0 to 1/n of (1 - n * t)^(n - 1) dtSubstitute
u = 1 - n * t, sodu = -n dt(dt = -du / n). Astgoes from0to1 / n,ugoes from1to0:E[X] = (1 / n) * integral from u = 0 to 1 of u^(n - 1) du = (1 / n) * [ u^n / n ] evaluated from u = 0 to 1 = (1 / n) * (1 / n) = 1 / n^2For
n = 200(Example 1),E[X] = 1 / 40,000 = 0.000025. Even though the200gaps average1 / 200 = 0.005, taking the smallest of200random gaps divides by200a second time.Poisson-process approximation for small d
When
nis large and we inspect tiny distancesd, thenpoints behave locally like a Poisson process (memoryless arrivals at average densitynper unit length). In a rate-nPoisson process, each inter-arrival gap follows anExponential(n)distribution, exceedingdwith probabilitye^(-n * d).Treating all
ncircular gaps as roughly independentExponential(n)variables makes the probability that allnexceedd:P(X > d) ≈ (e^(-n * d))^n = e^(-n^2 * d)Notice how this matches the exact formula when
n * dis tiny:(1 - n * d)^(n - 1) ≈ (e^(-n * d))^(n - 1) ≈ e^(-n^2 * d), meaningXbehaves approximately like anExponential(n^2)variable with mean1 / n^2.def poisson_closest_pair_approximation(n: int, d: float) -> float: """Return the Poisson-process approximation e^(-n^2 * d) for P(X > d) when d >= 0.""" # An exponential waiting gap is non-negative, so P(X > d) is 1.0 whenever d <= 0. if d <= 0.0: return 1.0 # Treating the n gaps as roughly independent Exponential(n) variables gives (e^(-n * d))^n = e^(-n^2 * d). return exp(-n * n * d)Walk through the three examples
Comparing how the formulas behave across the three examples:
- Example 1 (
n = 200, d = 0.000005, days = 365):days = 365givesminimum_people = 23(approx ≈ 22.4944). Around the loop,E[X] = 1 / 40,000 = 2.5e-5, and sincen * d = 0.001is tiny, exact0.999^199 ≈ 0.819468and Poissone^(-0.2) ≈ 0.818731agree within0.09%. - Example 2 (
n = 100, d = 0.002, days = 400):days = 400bumpsminimum_peopleto24(approx ≈ 23.5482). Around the loop,n * d = 0.2reserves 20% of the entire circle, so the sum-to-1competition drives exact0.8^99 ≈ 2.55e-10nearly 8x below Poissone^(-20) ≈ 2.06e-9. - Example 3 (
n = 4, d = 0.15, days = 30): On a30-day calendar,minimum_people = 7(approx ≈ 6.4489). Withn = 4,E[X] = 1 / 16 = 0.0625, exact(1 - 0.6)^3 = 0.064, and Poissone^(-2.4) ≈ 0.0907(off becausen = 4is small andn * d = 0.6is large).
- Example 1 (
Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple from math import exp, log, sqrt def minimum_people_for_shared_birthday(days: int) -> int: """Return the smallest group size n where P(at least two share a birthday) > 0.5.""" # prob_all_distinct tracks P(all people so far have different birthdays), starting at 1.0 for 0 people. prob_all_distinct = 1.0 people = 0 # P(shared birthday) > 0.5 is equivalent to P(all distinct) < 0.5. # Use >= 0.5 (not > 0.5) so an exact 0.5 tie (which happens when days == 2, people == 2) keeps adding a person. while prob_all_distinct >= 0.5: people += 1 # Person `people` must land on one of the `days - (people - 1)` days not yet taken. available_days = days - (people - 1) prob_all_distinct *= available_days / days return people def prob_closest_pair_farther_than(n: int, d: float) -> float: """Return exact P(minimum circular distance X among n uniform points on a length-1 circle > d).""" # Distances between distinct random points are strictly positive, so X > d is certain when d <= 0. if d <= 0.0: return 1.0 # All n adjacent arcs around the circle must each exceed d, requiring n * d < 1 total buffer length. if n * d >= 1.0: return 0.0 # Removing n mandatory buffers of length d leaves (1 - n * d) of slack across (n - 1) free coordinates. remaining_circle_fraction = 1.0 - n * d return remaining_circle_fraction ** (n - 1) def poisson_closest_pair_approximation(n: int, d: float) -> float: """Return the Poisson-process approximation e^(-n^2 * d) for P(X > d) when d >= 0.""" # An exponential waiting gap is non-negative, so P(X > d) is 1.0 whenever d <= 0. if d <= 0.0: return 1.0 # Treating the n gaps as roughly independent Exponential(n) variables gives (e^(-n * d))^n = e^(-n^2 * d). return exp(-n * n * d) def birthday_collision_and_spacing(n: int, d: float, days: int = 365) -> Dict[str, float]: # Part 1: exact collision threshold and its Taylor-expansion approximation sqrt(2 * days * ln(2)). min_people = minimum_people_for_shared_birthday(days) approx_min_people = sqrt(2.0 * days * log(2.0)) # Part 2: integrating P(X > t) = (1 - n * t)^(n - 1) from t = 0 to 1/n yields E[X] = 1 / n^2. expected_min_spacing = 1.0 / (n * n) # Part 3: exact circular tail probability P(X > d) and its small-d Poisson approximation. exact_tail_prob = prob_closest_pair_farther_than(n, d) poisson_tail_prob = poisson_closest_pair_approximation(n, d) return { "minimum_people": min_people, "approximate_minimum_people": approx_min_people, "expected_minimum_spacing": expected_min_spacing, "probability_closest_distance_greater_than_d": exact_tail_prob, "poisson_approximation": poisson_tail_prob, }✅ Submit now — all tests should pass.
Intuition & how it works
Think of dropping n pins at random around a circular track of perimeter 1 — or assigning m birthdays across a 365-day calendar. Intuition often guesses that collisions need roughly half of 365 people (around 183), and that the closest pair of n pins sits about 1 / n apart. Both guesses miss the same quadratic effect: you are not comparing pins against one fixed mark, you are comparing every pair of pins against each other, and n pins form n * (n - 1) / 2 ≈ n^2 / 2 pairs! That n^2 pair count powers the birthday paradox (the fact that collisions become likely once group size reaches the square root of the calendar size, not half of it), and explains why the minimum of n circular gaps shrinks to 1 / n^2 even though an average gap has length 1 / n.
Attempting to sum collision probabilities directly across all possible tie patterns (one matching pair, two separate pairs, a triple tie, and so forth) tangles you in inclusion-exclusion algebra, while random Monte Carlo sampling produces noisy estimates and misses tiny tail probabilities like 2.55e-10 in Example 2. Instead, we flip both questions to their complement (the opposite event, whose probability is 1 minus the original): "no two people share a day" is a sequential product of shrinking fractions, and "no two pins sit within d" means all n adjacent arcs exceed d, shrinking the available free perimeter to (1 - n * d)^(n - 1).
Let's trace a compact example with a 4-day mini-calendar (days = 4) and n = 4 circular pins at cutoff d = 0.15:
- Calendar threshold (days = 4): Person 1 avoids a match with probability 4/4 = 1.0. Person 2 avoids Person 1 with 3/4 = 0.75 (still >= 0.5). Person 3 avoids both with 3/4 * 2/4 = 0.375 < 0.5, meaning P(match) = 0.625 > 0.5, so minimum_people = 3 (close to the Taylor expansion estimate sqrt(2 * 4 * ln(2)) ≈ 2.35, where a Taylor expansion approximates a smooth function near zero with a low-degree polynomial like e^(-x) ≈ 1 - x).
- Circular spacing (n = 4, d = 0.15): Reserving 4 buffers of 0.15 leaves 1 - 4 * 0.15 = 0.4 of free perimeter across 4 - 1 = 3 coordinates, so P(X > 0.15) = 0.4^3 = 0.064, E[X] = 1 / 4^2 = 0.0625, and the Poisson process estimate (modeling points as memoryless random arrivals at density n) gives e^(-4^2 * 0.15) = e^(-2.4) ≈ 0.0907.
Complexity
- Time:
O(sqrt(days)). Findingminimum_peoplemultiplies one fraction per person added untilprob_all_distinctdrops below0.5, taking roughlysqrt(2 * ln(2) * days) ≈ 1.18 * sqrt(days)loop steps (23steps fordays = 365). All four remaining dictionary entries evaluate closed-form formulas (sqrt,log,**, andexp) inO(1)time regardless ofn. - Space:
O(1). Only scalar counters and floats are updated in place before returning a fixed five-key dictionary.
Edge cases
days = 1: By the pigeonhole principle, the 2nd person is guaranteed to match the 1st (prob_all_distinctdrops from1.0to0.0), sominimum_peopleis2.days = 2(exact0.5tie): With 2 people,P(shared)equals0.5, which is not strictly above0.5, sowhile prob_all_distinct >= 0.5advances to3people. Remarkably,days = 2is the only calendar size with an exact0.5tie:2 * (D - 1) * ... * (D - m + 1) = D^(m - 1)requiresD - 1to divideD^(m - 1), and sinceD - 1is coprime toD, we must haveD - 1 = 1.n * d >= 1: Fittingnarcs each strictly longer thandwould exceed the perimeter1. Returning0.0explicitly prevents(1 - n * d) ** (n - 1)from raising a negative base to an even power and returning a bogus positive number (such as(-0.5)^2 = 0.25atn = 3, d = 0.5).d <= 0: Arc lengths between distinct continuous random points are strictly positive, so both exactP(X > d)and the exponential distribution estimate (the memoryless continuous waiting-time curveP(Y > d) = e^(-rate * d)ford >= 0) clamp to1.0.n = 2: Two points divide the loop into two complementary arcsUand1 - U, making the shorter arc uniform on[0, 0.5]withE[X] = 0.25andP(X > d) = 1 - 2 * dfor0 <= d <= 0.5.
Common mistakes
- Using a non-wrapping interval
[0, 1]instead of a perimeter-1circle. On a flat segment[0, 1], the outer margins before the minimum point and after the maximum point are not pairwise distances, changing the formulas toP(X > d) = (1 - (n - 1) * d)^nandE[X] = 1 / (n^2 - 1)(1/3instead of0.25atn = 2). - Confusing the mean gap
1 / nwith the expected minimum gap1 / n^2. Allncircular arcs sum to1so their average is always1 / n; taking the minimum ofnrandom arcs introduces a second factor of1 / n. - Looping
while prob_all_distinct > 0.5instead of>= 0.5. Stopping at0.5solvesP(shared) >= 0.5instead of strictP(shared) > 0.5, returning2instead of3whendays = 2. - Treating the
ncircular gaps as independent in the exact formula. Becauseg_1 + ... + g_n = 1is fixed, enlarging one arc squeezes the remaining arcs; ignoring that sum-to-1coupling is precisely what turns exact(1 - n * d)^(n - 1)into Poissone^(-n^2 * d). - Solving
m * (m - 1) = 2 * D * ln(2)instead ofm^2 = 2 * D * ln(2). Keeping the-mterm yields22.9999atD = 365, whereas the standard closed-form approximation drops-mto givesqrt(2 * D * ln(2)) ≈ 22.4944.
Follow-up questions
- Does seasonal unevenness in daily birth rates make a shared birthday more likely or less likely than under a uniform calendar? Non-uniform daily probabilities always make a collision more likely (or equal), never less likely, so
minimum_peoplecan only stay the same or drop. For 2 people with day probabilitiesp_1, ..., p_Dsumming to1,P(match) = sum(p_i^2) = 1/D + sum((p_i - 1/D)^2), which attains its unique minimum atp_i = 1/Dbecause squared deviations are non-negative. By symmetric polynomial majorization (Schur-concavity of elementary symmetric polynomials), concentrating mass onto busier days reducesP(all m distinct)for every group sizem, though realistic+-10%seasonal birth swings barely nudgeP(match)atm = 23from0.507to~0.509. - Across a group of m people on a D-day calendar, how many pairs of individuals are expected to share the same birthday? A group of
mpeople containsC(m, 2) = m * (m - 1) / 2distinct pairs, and each pair collides with probability1 / D. By linearity of expectation (the property that the expected sum of random indicator variables equals the sum of their individual expectations, even when the indicators are correlated), the expected count of matching pairs ism * (m - 1) / (2 * D). Atm = 23andD = 365, this equals253 / 365 ≈ 0.6931 ≈ ln(2): modeling rare pair matches asPoisson(ln(2))givesP(0 matches) ≈ e^(-ln(2)) = 0.5. - How would you write a Monte Carlo simulation in Python to empirically validate the minimum circular gap formulas? In each trial, draw
nindependent uniform floats on[0, 1), sort them aspts, compute then - 1adjacent differencespts[i + 1] - pts[i], and include the wrap-around gap1.0 - pts[-1] + pts[0]before takingmin(gaps). Vectorizing50,000trials in NumPy forn = 200estimatesE[X] = 1 / 40,000 = 2.5e-5via the sample mean of minimum gaps (to< 0.5%standard error) and estimatesP(X > d)via the empirical fraction of trials whose minimum gap exceedsd.
Follow-up questions
- Does seasonal unevenness in daily birth rates make a shared birthday more likely or less likely than under a uniform calendar?
- Across a group of m people on a D-day calendar, how many pairs of individuals are expected to share the same birthday?
- How would you write a Monte Carlo simulation in Python to empirically validate the minimum circular gap formulas?
Similar questions
- Continuity-Corrected Normal Estimate for Binomial Upper Tails
- Exact and Poisson Tail Probabilities for Rare Trials
- Continuous vs. Block Coin Tossing for a Run of Heads
- Probability of Collecting At Least Two Red Balls
- Drawing Three Kept Balls with Green Replacements
- Winner Detection for a Connect Four Move Sequence
More Virtu Financial interview questions
- Continuity-Corrected Normal Estimate for Binomial Upper Tails Hard
- Exact and Poisson Tail Probabilities for Rare Trials Hard
- Continuous vs. Block Coin Tossing for a Run of Heads Hard Pro
- Drawing Three Kept Balls with Green Replacements Medium Pro
- Winner Detection for a Connect Four Move Sequence Medium Pro
- Largest Triangle-Free Simple Graph Construction Hard Pro
- Peak-Shaped Skyline With Largest Combined Height Hard Pro
- Fewest Payments Needed to Clear Group Balances Hard Pro
- Coordinate Pair Reachability Under Sum Updates Hard Pro
- Probability of Collecting At Least Two Red Balls Medium Pro