Problem Breakdown
Route Planner
Published ยท
medium
Try This Problem Yourself
Practice in the AI-enabled editor with real-time feedback
You're given a Network of stations connected by edges. Each edge carries a travel time (in minutes) and a line name ("Blue", "Express", etc.). Some edges are one-way. The main planner method takes a start and end station and returns the route that minimizes total travel time, where switching lines costs an extra 5 minutes per transfer. A second planner method takes the same inputs plus a cap on how many times you can switch lines.
On the shipped test map, three routes exist from Central to Airport.
Green: Central โ Park โ Airport 4 + 6 = 10 min
Red: Central โ Harbor โ Airport 5 + 3 = 8 min
Blue: Central โ Mall โ Stadium โ Airport 2 + 3 + 2 = 7 min (best)The Blue route wins with three hops, even though by hop count you'd pick the two-hop Red route.
That transfer penalty looks like a small detail, but it's the thing the whole problem turns on. It means the cost of your next edge depends on which line you arrived on, and that single fact is what trips up every solution short of the last one.
Solution 1, BFS by hop count
BFS is the first algorithm most people reach for when they hear "shortest path". The template is short. You keep a queue of partial paths and a visited set of stations. On each step you pop the front of the queue and push every unvisited neighbor onto the back. The search stops the first time the destination comes off the queue, and that's the returned path.
Complexity
Where it breaks
Solution 2, Dijkstra keyed on station
Where it breaks
Solution 3, Dijkstra keyed on (station, line)
Solution 4, Dijkstra keyed on (station, line, transfers)
Complexity
Where it lands
Benchmarks (Python)
Takeaways
Purchase Premium to Keep Reading
Unlock this article and so much more with Hello Interview Premium