Expected Passenger Wait Across Repeating Transit Headways
Hard · Statistics & Math · Software Engineer · Technical Screen
Problem Statement
Two transit routes, A and B, run continuously along the same corridor. Each route follows a deterministic, endlessly repeating cycle of integer departure intervals (headways in minutes between back-to-back vehicles), given by gaps_a and gaps_b. Vehicles spend negligible dwell time at the station, and a rider walks onto the platform at a uniformly random clock instant across the operating cycle without checking any schedule, boarding the first vehicle that arrives.
Implement compare_expected_waits(gaps_a, gaps_b) to compute each route's expected waiting time in minutes and identify the better option when judged strictly by expected wait (ignoring wait-time variance, maximum possible delay, and crowding).
Return a dictionary with three keys:
"wait_a": floating-point expected waiting time for Route A."wait_b": floating-point expected waiting time for Route B."preferable":"A"if Route A has a strictly smaller expected wait,"B"if Route B has a strictly smaller expected wait, or"tie"if both expected waits are equal.
If either input schedule is empty, contains a negative interval, or sums to zero total cycle duration, raise a ValueError.
def compare_expected_waits(gaps_a: List[int], gaps_b: List[int]) -> Dict[str, object]:
Examples
Example 1
Input: gaps_a = [8], gaps_b = [2, 8, 14]
Output: {"wait_a": 4.0, "wait_b": 5.5, "preferable": "A"}
Both routes average 8 minutes between departures ((2 + 8 + 14) / 3 = 8), yet their expected rider waits differ. On Route A, every arrival falls inside an 8-minute window with average wait 8 / 2 = 4.0 minutes. On Route B's 24-minute cycle, a random arrival lands in the 2-, 8-, and 14-minute windows with probabilities 2/24, 8/24, and 14/24, waiting 1.0, 4.0, and 7.0 minutes on average inside each window: (2/24)*1 + (8/24)*4 + (14/24)*7 = 132 / 24 = 5.5 minutes. Route "A" has the shorter expected wait.
Example 2
Input: gaps_a = [3, 9], gaps_b = [4, 4, 8]
Output: {"wait_a": 3.75, "wait_b": 3.0, "preferable": "B"}
Route A repeats a 12-minute cycle (3 + 9) with expected wait (3^2 + 9^2) / (2 * 12) = 90 / 24 = 3.75 minutes. Route B repeats a 16-minute cycle (4 + 4 + 8) with expected wait (4^2 + 4^2 + 8^2) / (2 * 16) = 96 / 32 = 3.0 minutes, making Route "B" preferable.
Constraints
gaps_aandgaps_bare lists of integers representing headway durations (in minutes) over one repeating cycle.- A valid schedule has
len(gaps) >= 1,gap >= 0for every entry, andsum(gaps) > 0; invalid schedules must raiseValueError. - Individual intervals may be up to
10^6, so comparing two distinct schedules with nearly identical expected waits must not lose precision to floating-point rounding. - Station dwell time is zero, each cycle repeats forever, and passenger arrival times are independent of departure schedules.
Step-by-step walkthrough
Pin down the probability model and contract
Each route is described by the list of headways (intervals in minutes between consecutive departures) in one repeating cycle—for instance,
gaps_a = [8]for Route A andgaps_b = [2, 8, 14]for Route B in Example 1. A rider walks onto the platform at a uniformly random clock moment and boards the next departing vehicle. We wantcompare_expected_waits(gaps_a, gaps_b)to return:"wait_a"and"wait_b": each route's expected waiting time in minutes,"preferable":"A"or"B"for the strictly smaller expected wait, or"tie"when equal.
Before writing formulas, make the modeling assumptions explicit:
- Repeating cycle of total length
T = sum(gaps): The headway list repeats endlessly with zero station dwell time. (Even if intervals were drawn at random with the same frequencies, the long-run expected wait turns out to be identical.) - Uniform random arrival: The rider's arrival offset inside
[0, T)is uniform and independent of departure times. - Validation and decision rule: Selection depends solely on expected wait (note that worst-case wait is
max(gaps):8min on Route A vs14min on Route B). An empty list, negative headway, or zero total cycle duration has no valid wait and raisesValueError.
Why "half the mean headway" is a trap
In Example 1, both routes average the exact same
8-minute headway: Route A has[8], and Route B averages(2 + 8 + 14) / 3 = 8minutes. It is tempting to guess that a random rider waits half of8minutes—4.0minutes—on both routes!Draw one
24-minute cycle of Route B on a timeline to see why that shortcut fails:One 24-minute cycle of Route B (departures at t = 0, 2, 10, 24): t: 0 2 10 24 |<->|<------>|<------------------>| 2m 8m 14m (2/24) (8/24) (14/24 = 7/12 > half of the entire cycle!)When you arrive at a uniformly random clock time in
[0, 24), you do not fall into the three intervals equally often:- You fall in the
2-minute interval with probability2 / 24 = 1/12(average wait inside it:1.0min). - You fall in the
8-minute interval with probability8 / 24 = 4/12(average wait inside it:4.0min). - You fall in the
14-minute interval with probability14 / 24 = 7/12(average wait inside it:7.0min).
Over half of all moments on the clock sit inside the
14-minute gap! This length-biased sampling effect is known as the inspection paradox: sampling a timeline at a random instant hits longer intervals proportionally more often than shorter ones.- You fall in the
Derive the exact expected wait formula
Suppose one cycle has headways
g_1, g_2, ..., g_kwith total durationT = sum(gaps):- Probability of landing in interval
g: Under uniform arrival on[0, T), an interval of durationgcaptures fractiong / Tof all arrivals. - Average wait inside interval
g: Conditional on landing inside an interval of lengthg, your arrival position is uniform from0(just missed a departure, waitg) tog(vehicle arriving right now, wait0), so your conditional mean wait isg / 2. - Sum across the cycle: Multiply each interval's arrival share by its conditional mean wait:
E[wait] = sum over g of (g / T) * (g / 2) = sum(g²) / (2 * T) Wait-time sawtooth across Route B's 24-minute cycle (triangle g has area g² / 2): 14 | |\ 8 | |\ | \ 2 |\ | \ | \ 0 |_\__|__\_____|___\___ 0 2 2 10 10 24 -> E[wait] = total triangle area / T = sum(g²) / (2 * T)Rewriting
sum(g²)in terms of the mean headwaym = T / kand population variancev = sum((g - m)²) / k(usingsum(g²) / k = m² + v) reveals the exact penalty for irregular spacing:E[wait] = m / 2 + v / (2 * m)The term
m / 2is the naive "half the mean gap" guess, whilev / (2 * m)is strictly positive whenever headways vary!- Probability of landing in interval
Work through Example 1 and Example 2 by hand
Apply
E[wait] = sum(g²) / (2 * T)to Example 1 (gaps_a = [8],gaps_b = [2, 8, 14]):- Route A (
[8]):T = 8andsum(g²) = 8² = 64, sowait_a = 64 / (2 * 8) = 4.0minutes. - Route B (
[2, 8, 14]):T = 2 + 8 + 14 = 24andsum(g²) = 4 + 64 + 196 = 264, sowait_b = 264 / (2 * 24) = 264 / 48 = 5.5minutes (5minutes30seconds). Route"A"wins.
In Example 2 (
gaps_a = [3, 9],gaps_b = [4, 4, 8]):- Route A (
[3, 9]):T = 12,sum(g²) = 9 + 81 = 90,wait_a = 90 / 24 = 3.75minutes. - Route B (
[4, 4, 8]):T = 16,sum(g²) = 16 + 16 + 64 = 96,wait_b = 96 / 32 = 3.0minutes. Route"B"wins.
- Route A (
Implement cycle validation and exact comparison
Write a helper
cycle_sums(gaps)that validates the schedule and accumulates(cycle_length, sum_of_squares)using exact Python integers so per-element float rounding never builds up.To pick
"preferable", comparesquares_a / (2 * total_a)againstsquares_b / (2 * total_b)by cross-multiplying the positive integers:squares_a * total_bvssquares_b * total_a. Arbitrary-precision Python integers never overflow and never confuse two nearly equal fractions (such as[1, 999999]vs[1000000]) for a tie.def cycle_sums(gaps: List[int]) -> Tuple[int, int]: """Return (cycle_length, sum_of_squared_gaps) as exact integers for one cycle.""" if not gaps: raise ValueError("a service needs at least one gap") cycle_length = 0 sum_of_squares = 0 for gap in gaps: if gap < 0: raise ValueError("gaps cannot be negative") cycle_length += gap sum_of_squares += gap * gap if cycle_length == 0: raise ValueError("the cycle length must be positive") return cycle_length, sum_of_squares def compare_expected_waits(gaps_a: List[int], gaps_b: List[int]) -> Dict[str, object]: # Phase 1: Sum each service's total cycle time T and squared gaps sum(g^2) in exact ints. total_a, squares_a = cycle_sums(gaps_a) total_b, squares_b = cycle_sums(gaps_b) # Phase 2: Compute expected waits. # A uniform random arrival lands in gap g with probability (g / total) and waits (g / 2) # on average inside that gap, so E[wait] = sum((g / total) * (g / 2)) = sum(g^2) / (2 * total). wait_a = squares_a / (2 * total_a) wait_b = squares_b / (2 * total_b) # Phase 3: Pick the smaller expected wait using exact integer cross-multiplication: # squares_a / (2 * total_a) < squares_b / (2 * total_b) <=> squares_a * total_b < squares_b * total_a. # Cross-multiplying avoids 64-bit float precision loss when two distinct waits are very close. left_product = squares_a * total_b right_product = squares_b * total_a if left_product < right_product: preferable = "A" elif right_product < left_product: preferable = "B" else: preferable = "tie" return { "wait_a": wait_a, "wait_b": wait_b, "preferable": preferable, }Sanity-check with a minute-by-minute trace
Whenever you derive a continuous probability formula, cross-check it on a discrete grid. Suppose a rider arrives at the midpoint of each of the
24minutes in Route B's cycle (t = 0.5, 1.5, ..., 23.5):2-min gap (t = 0.5 .. 1.5): waits 1.5 + 0.5 = 2.0 8-min gap (t = 2.5 .. 9.5): waits 7.5 + 6.5 + ... + 1.5 + 0.5 = 32.0 14-min gap (t = 10.5 .. 23.5): waits 13.5 + 12.5 + ... + 1.5 + 0.5 = 98.0 -------------------------------------------------------------------------- Total wait across all 24 midpoints = 2.0 + 32.0 + 98.0 = 132.0 Average wait = 132.0 / 24 = 5.5 minutesBecause remaining wait falls linearly inside every whole minute, the midpoint value equals the exact continuous average across that minute—independently confirming
5.5.Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple def cycle_sums(gaps: List[int]) -> Tuple[int, int]: """Return (cycle_length, sum_of_squared_gaps) as exact integers for one cycle.""" if not gaps: raise ValueError("a service needs at least one gap") cycle_length = 0 sum_of_squares = 0 for gap in gaps: if gap < 0: raise ValueError("gaps cannot be negative") cycle_length += gap sum_of_squares += gap * gap if cycle_length == 0: raise ValueError("the cycle length must be positive") return cycle_length, sum_of_squares def compare_expected_waits(gaps_a: List[int], gaps_b: List[int]) -> Dict[str, object]: # Phase 1: Sum each service's total cycle time T and squared gaps sum(g^2) in exact ints. total_a, squares_a = cycle_sums(gaps_a) total_b, squares_b = cycle_sums(gaps_b) # Phase 2: Compute expected waits. # A uniform random arrival lands in gap g with probability (g / total) and waits (g / 2) # on average inside that gap, so E[wait] = sum((g / total) * (g / 2)) = sum(g^2) / (2 * total). wait_a = squares_a / (2 * total_a) wait_b = squares_b / (2 * total_b) # Phase 3: Pick the smaller expected wait using exact integer cross-multiplication: # squares_a / (2 * total_a) < squares_b / (2 * total_b) <=> squares_a * total_b < squares_b * total_a. # Cross-multiplying avoids 64-bit float precision loss when two distinct waits are very close. left_product = squares_a * total_b right_product = squares_b * total_a if left_product < right_product: preferable = "A" elif right_product < left_product: preferable = "B" else: preferable = "tie" return { "wait_a": wait_a, "wait_b": wait_b, "preferable": preferable, }✅ Submit now — all tests should pass.
Intuition & how it works
Imagine tossing a dart blindfolded at a 24-inch yardstick divided into three back-to-back segments of 2, 8, and 14 inches. Although the three segments average 8 inches in length, the 14-inch segment spans more than half the stick—so your dart hits the 14-inch segment seven times as often as the 2-inch segment. Probability theory calls this the inspection paradox (when you sample a timeline at a uniformly random moment, wider intervals cover proportionally more clock time and capture correspondingly more arrivals than narrow ones).
A naive guess sees that Route A ([8]) and Route B ([2, 8, 14]) both average 8 minutes between vehicles and concludes a random rider waits 8 / 2 = 4.0 minutes on either route. That treats all three headways as equally likely (1/3 each), which would only be true if the rider chose one of the three departures uniformly at random rather than walking up at a random clock time. Weighting each interval g by its share of cycle time g / T and multiplying by the g / 2 average wait inside that interval produces the true expected wait sum(g²) / (2 * T).
Walk through Example 1 (gaps_a = [8], gaps_b = [2, 8, 14]):
- Route A has cycle duration
T_A = 8and squared sum8² = 64, givingwait_a = 64 / (2 * 8) = 4.0minutes. - Route B has cycle duration
T_B = 2 + 8 + 14 = 24: a rider lands in2(2/24chance,1.0min mean wait),8(8/24chance,4.0min mean wait), or14(14/24chance,7.0min mean wait), givingwait_b = (4 + 64 + 196) / (2 * 24) = 264 / 48 = 5.5minutes. - Cross-multiplying
64 * 24 = 1536 < 264 * 8 = 2112confirms Route"A"has the smaller expected wait.
Complexity
Let k = len(gaps_a) + len(gaps_b) be the combined number of headway entries across both schedules.
- Time:
O(k). We iterate throughgaps_aonce andgaps_bonce to accumulatecycle_lengthandsum_of_squares, followed byO(1)arithmetic operations. - Space:
O(1)auxiliary space. Only a handful of scalar integers and floats are held in memory regardless of schedule length.
Edge cases
- Single constant headway
[g]:g² / (2 * g)simplifies tog / 2, matching a uniform wait over[0, g]. - Reordered intervals inside a cycle (
[14, 2, 8]vs[2, 8, 14]): Addition is commutative, so permuting the order of headways within a repeating cycle leaves expected wait unchanged. - Ties from distinct schedules (
[2, 6]vs[5]):[2, 6]yields(4 + 36) / (2 * 8) = 40 / 16 = 2.5, tying[5]'s25 / 10 = 2.5; cross-multiplying40 * 5 == 25 * 8(200 == 200) detects exact ties cleanly. - Back-to-back vehicles (
gap == 0alongside positive gaps): A0-minute headway occupies zero clock time (0 / T = 0) and adds0to bothcycle_lengthandsum_of_squares. - Invalid schedules (empty list, negative interval, or all-zero cycle): Rejected with
ValueErrorinstead of dividing by zero. - Near-ties with large intervals (
[1000000]vs[1, 999999]):[1, 999999]waits499999.000001vs500000.0; exact integer cross-multiplication preserves full precision even when float quotients round to the same 64-bit value.
Common mistakes
- Returning
mean(gaps) / 2(4.0minutes for both in Example 1): Ignores time-weighted arrival probabilities and drops the variance penaltyVar(gaps) / (2 * mean(gaps)). - Averaging per-interval waits with equal weights (
(1.0 + 4.0 + 7.0) / 3 = 4.0): Algebraically equivalent tomean(gaps) / 2; each interval's wait must be weighted byg / T, not1 / k. - Assuming more vehicles per hour always lowers wait:
[1, 7]dispatches two vehicles every8minutes (mean gap4min, higher frequency than[5]), yet its expected wait is(1 + 49) / 16 = 3.125minutes—worse than[5]'s2.5minutes because7/8of arrivals land inside the7-minute gap. - Accumulating rounded floats per interval (
sum((g / T) * (g / 2))): Floating-point drift can turn an exact tie into a false winner; summing exact integers first eliminates intermediate rounding.
Alternative approaches
- Mean-variance identity (
m / 2 + v / (2 * m)): Computing the mean headwaymand population variancevyields the same value and directly illustrates why irregular vehicle spacing ("bus bunching") always increases average passenger waits at fixed frequency. - Midpoint Riemann sum / Monte Carlo simulation: Evaluating waits at whole-minute midpoints
0.5, 1.5, ..., T - 0.5gives the exact answer inO(T)time for integer headways (ideal for a test oracle), while random sampling approximates it with errorO(1 / sqrt(samples)).
Follow-up questions
- How do you derive and compare the variance of passenger waiting time for the two schedules? Conditional on landing inside an interval of length
g, remaining waitWis uniform on[0, g], so its second moment (expected squared wait) isintegral_0^g w² * (1/g) dw = g² / 3. Weighting across the cycle byg / TgivesE[W²] = sum(g³) / (3 * T), andVar(W) = E[W²] - (E[W])². In Example 1, Route A ([8]) hasE[W_A²] = 512 / 24 = 64 / 3, soVar(W_A) = 64 / 3 - 16 = 16 / 3 ≈ 5.33min² (standard deviation≈ 2.31min). Route B ([2, 8, 14]) hasE[W_B²] = (8 + 512 + 2744) / 72 = 136 / 3, soVar(W_B) = 136 / 3 - 5.5² = 181 / 12 ≈ 15.08min² (standard deviation≈ 3.88min)—nearly triple Route A's variance on top of a1.5-minute longer mean wait. - How does the expected wait change when different headway lengths occur with unequal frequencies or are drawn randomly instead of repeating in a fixed order? If headway
g_joccurs with weight or frequencyf_j, both its cycle-time share and squared contribution scale byf_j, producingE[W] = sum(f_j * g_j²) / (2 * sum(f_j * g_j))(repeating an entryf_jtimes ingapsalready evaluates this). Requiring Route B's{2, 8, 14}headways to beat Route A's4.0-minute wait (E[W] < 4) simplifies to4 f_2 + 64 f_8 + 196 f_14 < 16 f_2 + 64 f_8 + 112 f_14, which cancelsf_8entirely and leavesf_2 > 7 * f_14:2-minute gaps must occur more than seven times as often as14-minute gaps! By the renewal-reward theorem (a probability law stating that the long-run time average over independent random cycles equals expected reward per cycle divided by expected cycle duration), drawing headwaysGindependently at random yields the exact same long-run formulaE[G²] / (2 * E[G]).
Follow-up questions
- How do you derive and compare the variance of passenger waiting time for the two schedules?
- How does the expected wait change when different headway lengths occur with unequal frequencies or are drawn randomly instead of repeating in a fixed order?
Similar questions
- Contrasting Linux Containers with Hardware Virtualization
- Mechanics and Trade-Offs of SGD vs. Adam
- Lifecycle of Running ls -l in a Linux Shell
- Arithmetic Square Root and In-Place Parity Partitioning
- Largest Manhattan Distance Across Matched Slices
- Mentoring a Student on Indexing or Async Execution
More Deshaw interview questions
- Contrasting Linux Containers with Hardware Virtualization Medium
- Lifecycle of Running ls -l in a Linux Shell Medium
- Mechanics and Trade-Offs of SGD vs. Adam Hard Pro
- Arithmetic Square Root and In-Place Parity Partitioning Medium Pro
- Largest Manhattan Distance Across Matched Slices Medium Pro
- Mentoring a Student on Indexing or Async Execution Medium Pro