Minimum Arrival Time in a Scheduled Transit Network
Trees & GraphsModel answerLast updated
Find the earliest time a traveler can reach a destination station given a fixed train timetable, then reconstruct the full itinerary with transfers and waits.
Minimum Arrival Time in a Scheduled Transit Network
You have a complete timetable for a regional train network. Every train follows a fixed sequence of stops, each tagged with an integer arrival time (in minutes):
train_id -> [(station_name, time), (station_name, time), ...]
Times within a single train's schedule are strictly increasing. A traveler can board a train at a station at exactly the minute the train is listed there.
Input
trains: a dictionary mapping a train ID to its ordered list of(station, time)pairs.start: the name of the departure station.start_time: the integer minute at which the traveler arrives at the start station.dest: the name of the destination station.
Movement rules
- The traveler may wait at their current station; time advances to the next scheduled event there.
- Any train whose schedule lists the traveler's current station at the current time may be boarded.
- Once on a train, the traveler may ride it to any subsequent stop.
- At any stop, the traveler may disembark and immediately board a different train that is present at the same station and time.
- Your solution must terminate — unbounded minute-by-minute waiting is not acceptable.
Part 1
Return the earliest arrival time at dest, or None if it cannot be reached.
earliest_arrival(trains, start, start_time, dest) -> int | None
Part 2
Extend the solution to also return the full itinerary: the ordered list of legs, where each leg describes either a ride on a specific train (from one station/time to another) or a wait at a station. Return None if the destination is unreachable.
find_route(trains, start, start_time, dest)
-> (arrival_time, legs) | None
A leg is a dict with at minimum:
{"kind": "ride" | "wait", "train": str | None,
"from": (station, time), "to": (station, time)}
Example
trains = {
"T1": [("A", 0), ("B", 10), ("C", 20)],
"T2": [("B", 10), ("D", 15)],
"T3": [("A", 5), ("D", 30)],
}
earliest_arrival(trains, "A", 0, "D") # -> 15
# Route: ride T1 A→B (0→10), transfer to T2, ride T2 B→D (10→15)
earliest_arrival(trains, "A", 0, "C") # -> 20
# Route: ride T1 straight through A→B→C
Constraints
- Station names are non-empty strings; train IDs are unique strings.
- All times are non-negative integers; times within one train are strictly increasing.
- Up to ~1 000 trains, each with up to ~500 stops.
startmay not appear in the timetable at all (traveler arrives and no train ever calls there).start == destis a valid input.
Hints
Hint 1
Model each (station, time) pair as a node in a graph. From any such node there are two kinds of outgoing edges: ride to the next stop on the same train, or wait at the same station until the next scheduled event there. Because every edge strictly increases time, the first time you reach any node is already optimal — so Dijkstra (or even BFS ordered by time) works directly.
Hint 2
You don't need to track which train the traveler is currently on to find the optimal time. Boarding, transferring, and staying on a train all reduce to the same thing: taking a ride edge out of the current (station, time) node. Build an index from (station, time) to a list of trains present there, then iterate over their next stops to generate ride edges.
Hint 3
To avoid infinite waiting loops, build a sorted list of event times for each station and use binary search to jump to the next one. For path reconstruction in Part 2, store a parent pointer — (previous_node, edge_kind, train_id) — the first time each node is discovered. Walk the pointers back from the destination, reverse the list, then merge consecutive edges that share the same kind and train ID…
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This is a shortest-path problem on a time-expanded graph. Every (station, time) pair that appears in the timetable — plus the start state — becomes a node. There are two kinds of directed edges:
Ride edge: train T is listed at (s, t) and its next stop is (s', t'). This gives the edge (s, t) → (s', t') with cost t' - t.
Wait edge: from (s, t), jump to (s, t_next) where t_next is the next time any train calls at station s (found via binary search on a pre-sorted list of event times per station).
The key insight is that the traveler's current train ID is not part of the state. "Staying on train T" versus "getting off and re-boarding T" both consume the same ride edge out of (s, t). Train IDs only matter for printing the itinerary in Part 2.
Because every edge strictly increases time, no state is ever reached more expensive the second time. The first discovery is always optimal, so we mark states visited at push time (not pop time) and can stop as soon as the destination is dequeued.
Preventing infinite search
The naive reading of "wait one minute at a time" could loop forever. The fix: between two consecutive timetable events at a station, the traveler has no choices to make, so we skip directly to the next event using bisect_right on the sorted event-time list for that station. The only reachable states are the start state plus the O(E) timetable nodes (where E is total stops), so the search terminates.
Edge cases
start == dest: returnstart_timeimmediately before searching.start_timepredates all events at the start station: the wait edge advances to the first one.- Start station never appears in the timetable: only the start state exists; destination is unreachable unless it equals the start.
- Unreachable destination: return
None. - Loop lines (a train visits a station twice): handled because time is always strictly increasing and nodes are deduplicated.
Complexity
Let E = total number of (station, time) entries across all itineraries.
- States:
O(E) - Edges: each timetable entry contributes at most one ride edge and one wait edge →
O(E)edges total - Time:
O(E log E)— dominated by heap operations and building the sorted event lists - Space:
O(E)for indexes, heap, and parent map
Part 2: route reconstruction
At each push, store parent[new_node] = (prev_node, "ride"|"wait", train_id). After the search, walk the chain from the destination back to the start, reverse it, then merge consecutive entries with the same (kind, train_id) into a single leg. A change from one train to another is a transfer; an intervening wait leg means the traveler had to wait at the transfer station.
Common mistakes
- Marking states visited at pop time instead of push time. Since no state improves after first discovery here, pop-time marking wastes heap space and can re-expand nodes.
- Stepping minute by minute for waits — this is unbounded and misses the point of compressing to timetable events.
- Including the train ID in the state. It inflates the state space and is unnecessary for correctness.
- Forgetting that a train boarded at its very last stop has no outgoing ride edge.
Python Solution
import heapq
from bisect import bisect_right
from collections import defaultdict
def _build_index(trains):
# (station, time) -> list of (train_id, stop_index)
present = defaultdict(list)
# station -> sorted list of event times
times_at = defaultdict(set)
for tid, stops in trains.items():
for i, (station, t) in enumerate(stops):
present[(station, t)].append((tid, i))
times_at[station].add(t)
times_at = {s: sorted(ts) for s, ts in times_at.items()}
return present, times_at
def _search(trains, start, start_time, dest):
"""Core Dijkstra over (station, time) states.
Returns (end_state, parent_map) or (None, parent_map)."""
if start == dest:
return (start, start_time), {(start, start_time): None}
present, times_at = _build_index(trains)
src = (start, start_time)
parent = {src: None}
# heap entries: (time, station)
heap = [(start_time, start)]
while heap:
t, s = heapq.heappop(heap)
state = (s, t)
if s == dest:
return state, parent
# --- Ride edges ---
for tid, i in present.get(state, ()):
stops = trains[tid]
if i + 1 < len(stops):
nxt_station, nxt_time = stops[i + 1]
nxt = (nxt_station, nxt_time)
if nxt not in parent:
parent[nxt] = (state, "ride", tid)
heapq.heappush(heap, (nxt_time, nxt_station))
# --- Wait edge: jump to next event at this station ---
ts = times_at.get(s, [])
j = bisect_right(ts, t)
if j < len(ts):
nxt = (s, ts[j])
if nxt not in parent:
parent[nxt] = (state, "wait", None)
heapq.heappush(heap, (ts[j], s))
return None, parent
def earliest_arrival(trains, start, start_time, dest):
"""Part 1: return the earliest arrival time, or None."""
end, _ = _search(trains, start, start_time, dest)
return None if end is None else end[1]
def find_route(trains, start, start_time, dest):
"""Part 2: return (arrival_time, legs) or None.
Each leg: {kind, train, from, to}."""
end, parent = _search(trains, start, start_time, dest)
if end is None:
return None
# Reconstruct edge sequence by walking parent pointers.
edges = []
cur = end
while parent[cur] is not None:
prev, kind, tid = parent[cur]
edges.append((prev, cur, kind, tid))
cur = prev
edges.reverse()
# Merge consecutive edges that belong to the same leg.
legs = []
for prev, cur, kind, tid in edges:
if legs and legs[-1]["kind"] == kind and legs[-1]["train"] == tid:
legs[-1]["to"] = cur # extend existing leg
else:
legs.append({"kind": kind, "train": tid,
"from": prev, "to": cur})
return end[1], legs
def format_route(result):
"""Pretty-print the output of find_route."""
if result is None:
print("Destination unreachable.")
return
arrival, legs = result
for leg in legs:
frm, to = leg["from"], leg["to"]
if leg["kind"] == "ride":
print(f" Ride {leg['train']}: {frm[0]} @ t={frm[1]} → "
f"{to[0]} @ t={to[1]}")
else:
print(f" Wait at {frm[0]}: t={frm[1]} → t={to[1]}")
print(f" Arrive at t={arrival}")
# --- Example ---
if __name__ == "__main__":
trains = {
"T1": [("A", 0), ("B", 10), ("C", 20)],
"T2": [("B", 10), ("D", 15)],
"T3": [("A", 5), ("D", 30)],
}
print(earliest_arrival(trains, "A", 0, "D")) # 15
print(earliest_arrival(trains, "A", 0, "C")) # 20
print(earliest_arrival(trains, "A", 0, "X")) # None
format_route(find_route(trains, "A", 0, "D"))
# Ride T1: A @ t=0 → B @ t=10
# Ride T2: B @ t=10 → D @ t=15
# Arrive at t=15