Problem Breakdown
Route Planner
Graph Search & Pathfinding
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 the Red route only takes two. The Red route is what you'd pick if you ranked routes by hop count.
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
Complexity
Where it breaks
Solution 3, Dijkstra keyed on (station, line) with parent pointers
State expansion
Path reconstruction via parents
Complexity
Where it lands
Benchmarks (Python)
Takeaways
Purchase Premium to Keep Reading
Unlock this article and so much more with Hello Interview Premium
Reading Progress
On This Page