Reconstruct Itinerary
Difficulty: Hard · Pattern: Graphs (BFS / DFS) · LeetCode #332
Given airline tickets[i] = [from, to], reconstruct the itinerary that starts at "JFK" and uses every ticket exactly once. If several itineraries are valid, return the one that is smallest in lexical order when read as a single sequence. At least one valid itinerary is guaranteed.
Examples
text
[["MUC","LHR"],["JFK","MUC"],["SFO","SJC"],["LHR","SFO"]]
→ ["JFK","MUC","LHR","SFO","SJC"]
[["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],["ATL","JFK"],["ATL","SFO"]]
→ ["JFK","ATL","JFK","SFO","ATL","SFO"]Hints
- Using every edge exactly once is an Eulerian path.
- Greedy "always take the smallest destination" can get stuck in a dead end. Hierholzer's algorithm fixes that by adding a node to the route only when it has no tickets left.
Approach
Hierholzer's algorithm:
text
adj[u] = destinations sorted ascending (pop from the front, or sort descending and pop from the back)
visit(u):
while adj[u]: visit(adj[u].pop_smallest())
route.append(u) # post-order
answer = reversed(route)Why does post-order work? If the smallest choice leads into a dead end, that dead end is appended to route first and ends up last after reversing. It's exactly where a dead end has to go in an Eulerian path. Every edge is consumed once: O(E log E) for the sorting.
Complexity
Time: O(E log E). Space: O(E).
Python solution
from collections import defaultdict
def findItinerary(tickets):
adj = defaultdict(list)
for a, b in sorted(tickets, reverse=True):
adj[a].append(b)
route, stack = [], ["JFK"]
while stack:
while adj[stack[-1]]:
stack.append(adj[stack[-1]].pop())
route.append(stack.pop())
return route[::-1]JavaScript solution
function findItinerary(tickets) {
const adj = new Map();
for (const [a, b] of [...tickets].sort((x, y) => (x[1] < y[1] ? 1 : x[1] > y[1] ? -1 : 0))) {
if (!adj.has(a)) adj.set(a, []);
adj.get(a).push(b);
}
const route = [];
const visit = (u) => { const out = adj.get(u); while (out && out.length) visit(out.pop()); route.push(u); };
visit('JFK');
return route.reverse();
}