Reconstruct Itinerary (LeetCode 332): Solution and Explanation

Hard
Depth First Search
Graph
Eulerian Circuit

You have a pile of airline tickets, each a departure and arrival airport, and the trip starts at JFK. Use every ticket exactly once to form one itinerary, and if several exist, return the one that is smallest in lexical order.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

Using every ticket exactly once means walking every edge of a directed graph once, which is an Eulerian path. The lexical requirement suggests a greedy idea: from each airport, always fly to the alphabetically smallest destination you have left. The trouble is that greed can strand you. If the smallest choice leads to an airport with no outgoing tickets while other tickets remain, the itinerary dead-ends.

A backtracking search fixes that by undoing bad choices, but it can be exponential. Hierholzer's algorithm fixes it in linear time with one clever change: add an airport to the answer only when you are stuck there, meaning it has no unused outgoing tickets, and then reverse the answer at the end.

Why does that work? When DFS gets stuck, the stuck airport must be the final stop of the remaining path, so it belongs at the end of the itinerary. Any detour you took that dead-ended gets emitted early in post-order, which after reversal places it later in the route, exactly after the loop that brings you back. Visiting destinations in sorted order makes the reversed result lexically smallest. Sorting tickets in reverse lets you pop the smallest destination from the end of each list in O(1).

Approach: Hierholzer's algorithm with post-order DFS

  1. Sort the tickets in reverse order and append each destination to adj[src], so each list ends with its smallest destination.
  2. Define dfs(curr) that keeps popping the last destination from adj[curr] and recursing on it while the list is not empty.
  3. Once curr has no tickets left, append it to res.
  4. Call dfs("JFK").
  5. Reverse res to get the itinerary in travel order.

Step-by-step example

tickets = [["JFK","KUL"],["JFK","NRT"],["NRT","JFK"]]
  1. After reverse sorting, adj is JFK: [NRT, KUL] and NRT: [JFK]. Popping from the end gives the smallest destination first.
  2. dfs(JFK) pops KUL, the lexically smaller option. KUL has no tickets, so KUL is appended: res = [KUL].
  3. Back at JFK, the list still has NRT, so it pops NRT and recurses. NRT pops JFK, and JFK now has nothing left, so JFK is appended, then NRT: res = [KUL, JFK, NRT].
  4. Finally the original JFK call has no tickets left and is appended: res = [KUL, JFK, NRT, JFK].
  5. Reversing gives JFK, NRT, JFK, KUL. The greedy choice of KUL first would have stranded the trip, but post-order placed it last.

Code: Python, Java, C++

1class Solution:
2    def findItinerary(self, tickets: List[List[str]]) -> List[str]:
3        from collections import defaultdict
4        adj = defaultdict(list)
5        # Sort in reverse so we can pop() from end in O(1)
6        for src, dst in sorted(tickets, reverse=True):
7            adj[src].append(dst)
8
9        res = []
10        def dfs(curr):
11            while adj[curr]:
12                dfs(adj[curr].pop())  # O(1) pop from end
13            res.append(curr)
14
15        dfs("JFK")
16        return res[::-1]

Time and space complexity

Time

O(E log E)

Sorting the E tickets costs O(E log E), and the DFS then pops each ticket exactly once.

Space

O(E)

The adjacency lists hold every ticket, and the result and recursion stack each hold up to E + 1 airports.

Other approaches

Backtracking DFS (time O(E^d) worst case, space O(E))

Try destinations in sorted order, mark tickets as used and undo when you hit a dead end before using all tickets. The first complete path is the answer. Easy to understand but exponential in the worst case.

Iterative Hierholzer with a stack (time O(E log E), space O(E))

Push JFK on a stack; while the top has tickets, push its next destination, otherwise pop it into the result. It avoids recursion depth limits on long itineraries.

Common mistakes

  • Appending airports in pre-order (when first visited) instead of post-order produces dead-end routes like JFK, KUL, NRT, JFK.
  • Popping from the front of a Python list with pop(0) makes each pop linear; that is why the lists are built in reverse and popped from the end.
  • Sorting in ascending order and popping from the end visits the largest destination first and breaks the lexical requirement.
  • Marking airports as visited instead of consuming tickets fails because the same airport can and often must be visited several times.

Frequently asked questions

What algorithm solves Reconstruct Itinerary?

Hierholzer's algorithm for Eulerian paths. You walk edges with DFS, add an airport to the result when it has no unused outgoing edges and reverse the result at the end.

Why does the greedy smallest-first approach fail alone?

Taking the smallest destination can lead to an airport with no way out while tickets remain. Post-order recording moves that dead end to the end of the itinerary, where it belongs.

Why reverse the result?

Airports are recorded when DFS gets stuck, which happens from the end of the trip backward. Reversing turns that order into the forward itinerary.

What is the time complexity?

O(E log E) for sorting the tickets, plus O(E) for the DFS since every ticket is used once. The space is O(E) for the adjacency lists, the result and the recursion stack, which can be as deep as the number of tickets.