Earliest-Arrival Reachability on Timed Transit Routes
Trees & GraphsAuto-graded · 24 test casesLast updated
Tests whether a candidate can model time-respecting graph search over indexed transit routes to determine if a destination is reachable from a starting stop.
Earliest-Arrival Reachability on Timed Transit Routes
You are given a transit network as a list of routes. Each route is itself a list of stop names. The position of a stop within a route acts as its absolute departure time: a stop at index t is visited at time t. Every route begins operating at time 0.
A traveler begins at stop origin at time 0.
At any point the traveler may:
- Board a vehicle at their current stop, provided the vehicle visits that stop at the traveler's current time or later.
- Ride that same vehicle forward to any subsequent stop on its route (earlier stops on the same route cannot be revisited by riding backward).
- Disembark at any stop and wait there indefinitely.
- Board a different vehicle at the same stop at any future time.
Write can_reach_destination(routes, origin, destination) that returns True if the traveler can eventually arrive at destination, and False otherwise.
Key Rules
- A vehicle at a stop departs at exactly the time equal to its index in the route list.
- Travel is forward-only within a single route: you cannot ride a vehicle to an earlier index on the same route.
- Waiting at a stop is free and has no time limit; a traveler who arrives at stop S at time T can board any vehicle that visits S at any time ≥ T.
- If
originequalsdestination, the traveler is already there. originanddestinationare both guaranteed to appear at least once somewhere across all routes.
Constraints
1 ≤ len(routes) ≤ 5001 ≤ len(routes[i]) ≤ 1000for each routei- Stop names are non-empty strings.
- Total number of stop-visits across all routes: at most
500 × 1000 = 500 000 - Multiple routes may visit the same stop at the same or different times.
- A single route may list the same stop more than once.
Examples
Example 1
Input: can_reach_destination([['A', 'B', 'C'], 'A', 'C'], 'A', 'C')
Output: True
Example 2
Input: can_reach_destination([['A', 'X', 'B'], ['B', 'Y', 'C']], 'A', 'C')
Output: False
Example 3
Input: can_reach_destination([['A', 'B'], ['B', 'A']], 'A', 'A')
Output: True
Example 4
Input: can_reach_destination([['A', 'B', 'C'], ['C', 'B', 'A']], 'C', 'A')
Output: True
Hints
Hint 1
Build a lookup from each stop name to all the (time, route_id, position) triples where that stop appears — this lets you quickly find every vehicle you could board after arriving at a stop at time T.
Hint 2
Think in terms of earliest arrival: if you can reach stop S at time T1 and also at time T2 > T1, the later arrival is strictly worse because waiting is free. A min-heap ordered by arrival time naturally explores better states first.
Hint 3
When you board a vehicle at position p on a route, you can only continue forward (to positions > p). Track the earliest position at which each route has already been boarded so you never process the same forward segment twice.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Core Insight: Earliest Arrival Dominates
Because a traveler can wait at any stop for free, arriving at a stop earlier is always at least as good as arriving later. This means the full state we care about is simply (stop, earliest_time_we_can_be_here). We want to propagate the minimum arrival time to every reachable stop — a classic shortest-path structure.
Preprocessing
Build a dictionary that maps each stop name to a sorted list of (time, route_id, position) triples — one entry for every time a route visits that stop. Sorting by time lets us binary-search for the first vehicle we can board after arriving at a given time.
Algorithm (Dijkstra-style)
- Start the min-heap with
(0, origin). - Pop the stop with the smallest known arrival time.
- Binary-search that stop's visit list for entries with
time >= arrival_time— these are the vehicles the traveler can still catch. - For each such vehicle, ride it forward along its route and attempt to relax the arrival time at every subsequent stop (arrival time = the stop's position index in that route).
- Stops whose arrival time improves get pushed onto the heap.
- Return
Truethe moment the destination is popped (it carries the true earliest arrival),Falseif the heap empties.
Avoiding Redundant Work
A per-route boarded_at array records the earliest position in that route from which we've ever started a forward scan. If a new boarding opportunity is at a position ≥ that recorded position, the forward segment is already fully covered — skip it. When a new boarding is earlier, only scan up to the previously recorded position (the tail is covered). This keeps total work proportional to total stop-visits rather than routes × route_length².
Why It Is Correct
- Waiting is free: boarding any vehicle at time ≥ arrival captures all wait-and-board options.
- Forward-only travel: we only scan indices after the boarding position.
- No backward time travel: vehicles whose visit time is before the traveler's arrival are excluded by the binary search.
- Optimality: Dijkstra guarantees that the first time a stop is popped it carries the globally minimum arrival time, so we never revisit a stop with a worse time.
Complexity
Let V = total number of stop-visits across all routes (sum of all route lengths), and S = number of distinct stops.
- Preprocessing: O(V log V) to sort each stop's visit list.
- Main loop: each stop-visit is relaxed at most once per route scan, and each route segment is scanned at most once due to the
boarded_atguard. Total edge relaxations: O(V). - Heap operations: O(V log S) in the worst case.
- Overall: O(V log V) time, O(V) space.
Reference Solution
from bisect import bisect_left
import heapq
from typing import List
def can_reach_destination(routes: List[List[str]], origin: str, destination: str) -> bool:
# Trivial case: already there
if origin == destination:
return True
# Build stop -> sorted list of (visit_time, route_id, position_in_route)
visits: dict = {}
for route_id, route in enumerate(routes):
for pos, stop in enumerate(route):
visits.setdefault(stop, []).append((pos, route_id, pos))
for stop_visits in visits.values():
stop_visits.sort() # sort by visit_time (first element)
# Dijkstra over stops; state = (earliest_arrival_time, stop)
earliest: dict = {origin: 0}
heap = [(0, origin)]
# For each route, the earliest position at which we've boarded it.
boarded_at: List[int] = [-1] * len(routes)
while heap:
arrival_time, stop = heapq.heappop(heap)
if arrival_time != earliest.get(stop):
continue
if stop == destination:
return True
stop_visits = visits.get(stop, [])
first = bisect_left(stop_visits, (arrival_time, -1, -1))
for visit_time, route_id, board_pos in stop_visits[first:]:
prev_board = boarded_at[route_id]
if prev_board != -1 and board_pos >= prev_board:
continue
boarded_at[route_id] = board_pos
route = routes[route_id]
scan_end = len(route) if prev_board == -1 else prev_board
for later_pos in range(board_pos, scan_end):
later_stop = route[later_pos]
if later_pos < earliest.get(later_stop, float('inf')):
earliest[later_stop] = later_pos
heapq.heappush(heap, (later_pos, later_stop))
return False