Reconstruct Itinerary

HardEulerian pathLeetCode 332 ↗World 6-17
0:00 / 0:00

Use every plane ticket once, starting at JFK, in alphabetical order. Depth-first search, then add each airport once its tickets run out.

▼

The problem

LeetCode 332 (Hard). Given airline tickets [from, to], reconstruct the itinerary: start at JFK, use every ticket exactly once, and if several itineraries work, return the one that is smallest in lexical (alphabetical) order.

Examples on screen: - LeetCode's [["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],["ATL","JFK"],["ATL","SFO"]]: three trips use all five tickets; compared stop by stop, JFK ATL JFK SFO ATL SFO wins (trip 3 loses at stop 2, trip 2 at stop 3). - The greedy trap (illustrative) [["JFK","KUL"],["JFK","NRT"],["NRT","JFK"]] → JFK NRT JFK KUL: always taking the smallest ticket flies to KUL first and is stuck with two tickets unused; backtracking fixes it (fly, stuck, undo, fly, fly, fly).

TRY IT ON LEETCODE ▶

The solution

def findItinerary(tickets):
    graph = defaultdict(list)
    for a, b in sorted(tickets, reverse=True):
        graph[a].append(b)      # smallest goes last
    route = []
    def visit(a):
        while graph[a]:
            visit(graph[a].pop())   # smallest
        route.append(a)             # no tickets left
    visit("JFK")
    return route[::-1]

Transcript

Reconstruct Itinerary. You're handed a pile of plane tickets, each from one airport to another. Start at J F K, use every ticket exactly once, and if several trips work, return the one that comes first alphabetically.

Here are five tickets. They can be used up in three different trips. Compare them stop by stop. After J F K, Atlanta beats San Francisco, then J F K beats San Francisco. So J F K, Atlanta, J F K, San Francisco, Atlanta, San Francisco wins.

So why not always take the smallest ticket? From J F K, Kuala Lumpur beats Narita, so we fly there, and we're stuck, with two tickets unused. The naive fix backtracks: try the tickets in order, and at a dead end, undo and try the next. That can take exponential time.

Here's the better way. Using every ticket once is an Eulerian path, and Hierholzer's algorithm builds it. Keep taking the smallest ticket, but write an airport down only when it has no tickets left, filling the route from the end. Kuala Lumpur runs out first, so it lands last. Then the Narita loop fills in before it.

In code, sort each airport's tickets, so the smallest comes off first. Visit an airport: while it still has tickets, pop the smallest and visit there. When it runs out, append it to the route. Reverse the route at the end.

Try six tickets around Atlanta. From J F K, fly to Atlanta, and Atlanta's smallest ticket goes straight back to J F K. J F K is out of tickets, so it's written last. Back in Atlanta, two loops remain: Los Angeles and back, then San Francisco and back. Now Atlanta is out too, and as the visits unwind, every airport is written, right to left.

With E tickets, sorting takes order E log E time, then each ticket is flown once. The lists, the route and the recursion take order E space.

Take the smallest ticket, write it down when you're stuck, then reverse. That's Reconstruct Itinerary.