CodingNodes / Advanced Graphs / Reconstruct Itinerary System design Space play · ←→ step · R restart

Problem

You hold a pile of one-way flight tickets. Each ticket is a pair [from, to] of three-letter airport codes. Plan one trip that starts at "JFK" and uses every ticket exactly once.

If more than one trip works, return the one that is smallest when compared airport by airport in alphabetical order. Return the airports in the order they are visited. A valid trip is guaranteed to exist.

Constraints

  • 1 ≤ tickets.length ≤ 300
  • every airport code is three uppercase letters, and from ≠ to
  • at least one trip that starts at JFK and uses every ticket exactly once exists

Examples: pick one to animate

Solutions

TimeO(E log E) SpaceO(E)

Time: Sorting the E tickets costs O(E log E). After that every ticket is taken from the end of a list exactly once, and every airport is pushed and popped once per ticket.

Space: The graph holds every ticket, and the stack and the route together hold at most one entry per ticket plus the start.

Sort the tickets from largest to smallest and group them by departure airport, so taking the last ticket of a list always gives the smallest destination. Keep a stack of the walk so far, starting at JFK. If the airport on top still has a ticket, fly it and push the new airport. If it has none, that airport is final: no ticket can follow it. Move it to the route. Dead ends get written first, so the finished route is backwards; reversing it gives the trip. Because small destinations are tried first and a dead end is only written after everything that can still be flown from earlier airports has been, the result is the smallest valid trip.