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