Compute Earliest Bus Arrival
Company: Apple
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Quick Answer: This question evaluates proficiency with shortest-path algorithms and time-dependent graph modeling, focusing on reasoning about travel times combined with periodic departure schedules and waiting-time calculations.
Constraints
- 0 <= len(segments) <= 200000
- Each segment is a tuple (from_stop, to_stop, travel_time, wait_interval)
- 0 <= travel_time <= 10^9
- 1 <= wait_interval <= 10^9
- 0 <= start_time <= 10^9
- Stop names are strings
Examples
Input: ([("A", "B", 10, 5)], "A", "B", 0)
Expected Output: 10
Explanation: A bus leaves A for B at time 0, so the traveler departs immediately and arrives at time 10.
Input: ([("A", "B", 10, 5), ("B", "C", 7, 3), ("A", "C", 30, 10)], "A", "C", 6)
Expected Output: 28
Explanation: From A at time 6, the next A->B bus leaves at 10 and arrives at 20. From B at 20, the next B->C bus leaves at 21 and arrives at 28. The direct A->C route would arrive later at 40.
Input: ([("S", "A", 5, 4), ("A", "T", 5, 5), ("S", "T", 20, 1)], "S", "T", 0)
Expected Output: 10
Explanation: Going S->A arrives at time 5, and A->T departs exactly at time 5, so the total arrival time is 10. The direct route arrives at 20.
Input: ([("A", "B", 3, 2), ("C", "D", 4, 1)], "A", "D", 1)
Expected Output: -1
Explanation: There is no path from A to D, so the destination is unreachable.
Input: ([], "X", "X", 7)
Expected Output: 7
Explanation: If the source and target are the same, the traveler is already there at the starting time.
Input: ([("A", "B", 100, 1), ("A", "B", 3, 10)], "A", "B", 9)
Expected Output: 13
Explanation: The first segment can be taken immediately and arrives at 109. The second leaves at time 10 and arrives at 13, which is earlier.
Hints
- Model the stops as nodes in a directed graph. The tricky part is that the cost of taking an edge depends on the time you arrive at its starting node.
- A min-heap shortest-path algorithm works here if, for each edge, you compute the next departure time using modulo arithmetic.