KatInterview

Expected Wait Time for Repeating Train Schedules

Arrays & HashingAuto-graded · 15 test cases
HardAuto-gradedArrays & Hashingprobabilityexpected-valueinspection-paradox

Last updated

Calculate and compare expected waiting times for transit services with different repeating gap patterns using length-biased sampling.

You are analyzing two transit services to determine which offers shorter expected waiting times for passengers who arrive at random times without checking the schedule.

Each service runs on a repeating cycle defined by a sequence of gaps (in minutes) between consecutive arrivals. For example, a service with gaps [5, 10, 15] repeats a pattern where trains arrive 5 minutes apart, then 10 minutes apart, then 15 minutes apart, then the cycle repeats.

A passenger arrives at a uniformly random time during the operating cycle, independent of the schedule. Calculate the expected waiting time for each service and determine which one offers a shorter expected wait.

Task

Write a function that takes two lists of positive integers representing the gap sequences for Service A and Service B, and returns:

  • The expected waiting time for Service A
  • The expected waiting time for Service B
  • Which service is preferable (has shorter expected wait), or "Equal" if they are the same

Key Insight

When a passenger arrives uniformly at random over a repeating cycle, longer gaps are more likely to be encountered than shorter gaps—this is known as length-biased sampling or the inspection paradox. A gap of length g occupies g units of time in the cycle, so the probability of arriving during that gap is proportional to its length, not to the count of gaps.

Constraints

  • Each gap list contains between 1 and 100 positive integers
  • Each gap value is between 1 and 1000 minutes
  • Services repeat indefinitely
  • Passenger arrival is uniformly distributed over the cycle duration
  • Trains depart instantly (zero dwell time)
  • Return expected waits as floats; use exact string matching for the preferable field

Examples

Example 1

Input: compare_train_waits([10], [5, 10, 15])

Output: {'wait_a': 5, 'wait_b': 5.833333333333333, 'preferable': 'A'}

Hints

Hint 1

For a fixed interval of length g, a uniformly arriving passenger waits g/2 minutes on average—but which intervals does the passenger encounter?

Hint 2

Longer gaps take up more time in the cycle. The probability of arriving during a gap is proportional to the gap's length, not the number of gaps.

Hint 3

The formula involves the sum of squared gaps divided by twice the total cycle time. Derive this by weighting each gap's expected wait by its time proportion.