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_a and gaps_b are lists of integers representing headway durations (in minutes) over one repeating cycle.
  • A valid schedule has len(gaps) >= 1, gap >= 0 for every entry, and sum(gaps) > 0; invalid schedules must raise ValueError.
  • 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

  1. 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 and gaps_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 want compare_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): 8 min on Route A vs 14 min on Route B). An empty list, negative headway, or zero total cycle duration has no valid wait and raises ValueError.
  2. 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 = 8 minutes. It is tempting to guess that a random rider waits half of 8 minutes—4.0 minutes—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 probability 2 / 24 = 1/12 (average wait inside it: 1.0 min).
    • You fall in the 8-minute interval with probability 8 / 24 = 4/12 (average wait inside it: 4.0 min).
    • You fall in the 14-minute interval with probability 14 / 24 = 7/12 (average wait inside it: 7.0 min).

    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.

  3. Derive the exact expected wait formula

    Suppose one cycle has headways g_1, g_2, ..., g_k with total duration T = sum(gaps):

    1. Probability of landing in interval g: Under uniform arrival on [0, T), an interval of duration g captures fraction g / T of all arrivals.
    2. Average wait inside interval g: Conditional on landing inside an interval of length g, your arrival position is uniform from 0 (just missed a departure, wait g) to g (vehicle arriving right now, wait 0), so your conditional mean wait is g / 2.
    3. 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 headway m = T / k and population variance v = sum((g - m)²) / k (using sum(g²) / k = m² + v) reveals the exact penalty for irregular spacing:

    E[wait] = m / 2 + v / (2 * m)
    

    The term m / 2 is the naive "half the mean gap" guess, while v / (2 * m) is strictly positive whenever headways vary!

  4. 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 = 8 and sum(g²) = 8² = 64, so wait_a = 64 / (2 * 8) = 4.0 minutes.
    • Route B ([2, 8, 14]): T = 2 + 8 + 14 = 24 and sum(g²) = 4 + 64 + 196 = 264, so wait_b = 264 / (2 * 24) = 264 / 48 = 5.5 minutes (5 minutes 30 seconds). 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.75 minutes.
    • Route B ([4, 4, 8]): T = 16, sum(g²) = 16 + 16 + 64 = 96, wait_b = 96 / 32 = 3.0 minutes. Route "B" wins.
  5. 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", compare squares_a / (2 * total_a) against squares_b / (2 * total_b) by cross-multiplying the positive integers: squares_a * total_b vs squares_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,
        }
    
  6. 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 24 minutes 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 minutes
    

    Because remaining wait falls linearly inside every whole minute, the midpoint value equals the exact continuous average across that minute—independently confirming 5.5.

  7. 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]):

  1. Route A has cycle duration T_A = 8 and squared sum 8² = 64, giving wait_a = 64 / (2 * 8) = 4.0 minutes.
  2. Route B has cycle duration T_B = 2 + 8 + 14 = 24: a rider lands in 2 (2/24 chance, 1.0 min mean wait), 8 (8/24 chance, 4.0 min mean wait), or 14 (14/24 chance, 7.0 min mean wait), giving wait_b = (4 + 64 + 196) / (2 * 24) = 264 / 48 = 5.5 minutes.
  3. Cross-multiplying 64 * 24 = 1536 < 264 * 8 = 2112 confirms 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 through gaps_a once and gaps_b once to accumulate cycle_length and sum_of_squares, followed by O(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 to g / 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]'s 25 / 10 = 2.5; cross-multiplying 40 * 5 == 25 * 8 (200 == 200) detects exact ties cleanly.
  • Back-to-back vehicles (gap == 0 alongside positive gaps): A 0-minute headway occupies zero clock time (0 / T = 0) and adds 0 to both cycle_length and sum_of_squares.
  • Invalid schedules (empty list, negative interval, or all-zero cycle): Rejected with ValueError instead of dividing by zero.
  • Near-ties with large intervals ([1000000] vs [1, 999999]): [1, 999999] waits 499999.000001 vs 500000.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.0 minutes for both in Example 1): Ignores time-weighted arrival probabilities and drops the variance penalty Var(gaps) / (2 * mean(gaps)).
  • Averaging per-interval waits with equal weights ((1.0 + 4.0 + 7.0) / 3 = 4.0): Algebraically equivalent to mean(gaps) / 2; each interval's wait must be weighted by g / T, not 1 / k.
  • Assuming more vehicles per hour always lowers wait: [1, 7] dispatches two vehicles every 8 minutes (mean gap 4 min, higher frequency than [5]), yet its expected wait is (1 + 49) / 16 = 3.125 minutes—worse than [5]'s 2.5 minutes because 7/8 of arrivals land inside the 7-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 headway m and population variance v yields 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.5 gives the exact answer in O(T) time for integer headways (ideal for a test oracle), while random sampling approximates it with error O(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 wait W is uniform on [0, g], so its second moment (expected squared wait) is integral_0^g w² * (1/g) dw = g² / 3. Weighting across the cycle by g / T gives E[W²] = sum(g³) / (3 * T), and Var(W) = E[W²] - (E[W])². In Example 1, Route A ([8]) has E[W_A²] = 512 / 24 = 64 / 3, so Var(W_A) = 64 / 3 - 16 = 16 / 3 ≈ 5.33 min² (standard deviation ≈ 2.31 min). Route B ([2, 8, 14]) has E[W_B²] = (8 + 512 + 2744) / 72 = 136 / 3, so Var(W_B) = 136 / 3 - 5.5² = 181 / 12 ≈ 15.08 min² (standard deviation ≈ 3.88 min)—nearly triple Route A's variance on top of a 1.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_j occurs with weight or frequency f_j, both its cycle-time share and squared contribution scale by f_j, producing E[W] = sum(f_j * g_j²) / (2 * sum(f_j * g_j)) (repeating an entry f_j times in gaps already evaluates this). Requiring Route B's {2, 8, 14} headways to beat Route A's 4.0-minute wait (E[W] < 4) simplifies to 4 f_2 + 64 f_8 + 196 f_14 < 16 f_2 + 64 f_8 + 112 f_14, which cancels f_8 entirely and leaves f_2 > 7 * f_14: 2-minute gaps must occur more than seven times as often as 14-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 headways G independently at random yields the exact same long-run formula E[G²] / (2 * E[G]).

Follow-up questions

Similar questions

More Deshaw interview questions

All 7 Deshaw questions →