Rebuild the Travel Route
Medium · Topological Sort & Shortest Paths · about 30 min
A traveller kept every flight ticket from a trip but lost the plan. Each ticket in tickets is a string "FROM-TO" with two three-letter airport codes in capital letters, for example "SYD-MEL". The trip started at airport start and used every ticket exactly once (the same ticket may appear more than once). At least one such route exists.
Return the route as a list of airport codes, starting with start. If several routes use all the tickets, return the one that is alphabetically smallest when you compare the lists stop by stop.
0 <= len(tickets) <= 300.
Example: rebuild_itinerary(["HUB-AAA", "HUB-BBB", "BBB-HUB"], "HUB") → ["HUB", "BBB", "HUB", "AAA"] (going to AAA first would strand you there with tickets left).
Hints
- Every ticket is an edge you must use exactly once: this is an Euler path, not a shortest path.
- Always trying the smallest airport next is right, but you can still get stuck early. What should happen to an airport with no tickets left?
- Walk forward with a stack. When the airport on top has no unused tickets, move it to the route. Reverse the route at the end.
Learn the pattern first: the Topological Sort & Shortest Paths lesson.
More Topological Sort & Shortest Paths problems
- Finish Every Training Module (Easy)
- Alarm Across the Campus (Easy)
- Does One Skill Lead to Another? (Easy)
- Flip the Fewest One-Way Signs (Easy)
- Letters of a Made-Up Language (Medium)
- Fewest Terms to Graduate (Medium)
- Budget Trip With Few Layovers (Medium)
- The Gentlest Hike (Medium)
- Wire Up the Sensors (Medium)
- Pick the Quietest Depot (Medium)
- Cross Before the Flood (Hard)
- How Many Fastest Routes? (Hard)
- Earliest Launch Day (Hard)
- Toll Roads With Coupons (Hard)