Reconstruct Itinerary
Reconstruct Itinerary is LeetCode 332 (Hard). Each ticket [from, to] is one flight. Starting at "JFK", put the flights in order as one trip that uses every ticket exactly once.
- At least one valid trip is guaranteed.
- If several trips work, return the one that is smallest in dictionary order, read as a list of airports.
- The same ticket can appear more than once, and each copy must be used.
- 1 <= tickets.length <= 300
- tickets[i].length == 2
- fromi.length == 3
- toi.length == 3
- fromi and toi consist of uppercase English letters.
- fromi != toi
Intuition
Airports are nodes and tickets are directed edges, so the trip is an Eulerian path: a walk that uses every edge once. Hierholzer's algorithm finds one by walking until it gets stuck and adding each airport to the route only when it has no tickets left.
- Why stuck means last: at every airport except the final stop, tickets in and tickets out balance, so arriving always leaves a way out. The first dead end is the real end of the trip.
- Detours fit in: tickets skipped on the way are used when the search backs up, and their airports land in front of the dead end.
- Smallest order: always fly the alphabetically smallest unused ticket.
"Use every edge exactly once" is an Eulerian path. Hierholzer's algorithm (DFS that records a node after its edges run out, then reverses) builds it in one pass.
Approach
Before reading on, try the rule "always fly to the smallest destination" on JFK→KUL, JFK→NRT, NRT→JFK. Then decide what to do with an airport that has no tickets left while others are still unused. Aim for O(E log E).
Sort each airport's destinations
Sort the tickets in reverse and append each destination to graph[src]. Every list then ends with its smallest destination, so pop() takes the smallest one in O(1) and removes that ticket at the same time.
Fly until stuck
In visit(airport), keep popping the smallest destination and calling visit on it. The ticket is removed before the call, so no ticket can ever be used twice.
Add an airport once its tickets run out
When graph[airport] is empty, append the airport to route. Airports are added from the end of the trip backwards: the dead end first, then each airport that led to it.
Reverse the route
visit("JFK") returns last, so JFK is appended last. route[::-1] therefore starts at JFK and lists the trip in flying order.
Code in Python, C++ and Java
Common pitfalls
Adding the airport before flying on
route.append(airport)
while graph[airport]:
visit(graph[airport].pop())while graph[airport]:
visit(graph[airport].pop())
route.append(airport)That is a plain greedy walk. For [["JFK","KUL"],["JFK","NRT"],["NRT","JFK"]] it gives JFK, KUL, NRT, JFK, which needs a KUL → NRT flight nobody has. Adding on the way out gives JFK, NRT, JFK, KUL.
Sorting the wrong way for pop()
for src, dst in sorted(tickets):
for src, dst in sorted(tickets, reverse=True):
pop() takes the last item, so ascending lists hand out the largest destination first. On [["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],["ATL","JFK"],["ATL","SFO"]] this returns a valid trip starting JFK, SFO, but the answer starts JFK, ATL.
Storing destinations in a set
graph[src].add(dst)
graph[src].append(dst)
Two identical tickets collapse into one. For [["JFK","ATL"],["ATL","JFK"],["JFK","ATL"]] the set version returns JFK, ATL, JFK and skips a ticket; the answer is JFK, ATL, JFK, ATL.
Edge cases
[["JFK","ATL"]]ATL is stuck at once and goes on the route, then JFK; reversed, that is ["JFK", "ATL"].
[["JFK","ATL"],["ATL","JFK"],["JFK","SFO"]]Each visit to JFK pops its own ticket from the same list, so the second visit flies on to SFO. The answer is JFK, ATL, JFK, SFO.
Complexity
Reconstruct Itinerary FAQ
Why not DFS with backtracking?
Trying destinations in order and putting a ticket back when a branch fails also works, and the first full trip it finds is the answer. But a bad early choice can be retried many times, so the worst case is exponential. Hierholzer's algorithm never puts a ticket back.
Can it be written without recursion?
Yes. Keep a stack that starts with JFK. While the airport on top has tickets, push its smallest destination; when it has none, pop it onto the route. Reverse the route at the end. It is the same algorithm with the call stack made explicit.
When does an Eulerian path exist?
In a directed graph whose edges are all connected, every node needs as many edges in as out, except that the start may have one extra edge out and the end one extra edge in. LeetCode guarantees this for the tickets, so the search never fails.