We are given a list of airline tickets as [from, to] pairs. The man departs from "JFK". We need to reconstruct the itinerary (the order of flights) that uses all the tickets exactly once. If there are multiple valid itineraries, we should return the one with the smallest lexical order when read as a single string.
This is the classic "Reconstruct Itinerary" problem (Leetcode 332). It can be modeled as finding a specific path in a directed graph (each ticket is a directed edge from from to to). The requirement is to use all tickets exactly once, so we are looking for an Eulerian path (or specifically an Eulerian trail that starts at "JFK" and uses each edge exactly once). Since the graph is directed, we are looking for an Eulerian path in a directed graph. For such a path to exist, the graph must be connected (in the sense of underlying undirected graph) and at most one vertex has (out-degree) - (in-degree) = 1 (the start), at most one vertex has (in-degree) - (out-degree) = 1 (the end), and all others have equal in and out degrees. However, the problem guarantees that a valid itinerary exists (as per typical problem statement). But we still need to find the itinerary with the smallest lexical order.
The typical solution uses a greedy DFS (depth-first search) with backtracking (or more efficiently, using Hierholzer's algorithm for Eulerian path) but with a twist: we need to visit edges in lexical order. That's why we sort the destinations for each departure airport lexicographically. However, if we do a simple DFS greedy (always take the smallest lexical next airport) and backtrack when stuck, it works but might be inefficient. Actually, the standard efficient solution is to use a stack and do a post-order DFS (like Hierholzer) but by visiting neighbors in lexical order, we get the correct itinerary in reverse order.
Why process destinations in lexical order? Because we want the smallest lexical itinerary. However, note that if we always greedily pick the smallest lexical next airport, we might get stuck early (dead end) before using all tickets. For example, consider tickets: JFK -> ATL, JFK -> SFO, ATL -> JFK, SFO -> ATL. If we go JFK -> ATL first (since ATL < SFO), then from ATL -> JFK, then from JFK -> SFO, then SFO -> ATL, that uses all tickets. But consider: JFK -> ATL, JFK -> SFO, ATL -> SFO, SFO -> JFK. If we go JFK -> ATL first, then ATL -> SFO, then SFO -> JFK, then JFK -> SFO, that works. But what if we have: JFK -> A, JFK -> B, A -> JFK, B -> A. Lexical order: A < B. If we go JFK -> A, then A -> JFK, then JFK -> B, then B -> A? But B->A exists? Actually we have B->A. That works. But suppose: JFK -> A, JFK -> B, A -> B, B -> JFK. If we go JFK->A, then A->B, then B->JFK, then JFK->B? That uses all? Tickets: JFK->A, JFK->B, A->B, B->JFK. That's 4 tickets. If we take JFK->A, then A->B, then B->JFK, then we are at JFK and have used 3 tickets, but we still have ticket JFK->B unused? Actually we used JFK->A and A->B and B->JFK. That's three. The fourth is JFK->B. At JFK after returning from B->JFK, we can take JFK->B? But we already used B->JFK? Wait, we used B->JFK? That's a different ticket. But we have two tickets from JFK: JFK->A and JFK->B. We used JFK->A. After returning to JFK, we can use JFK->B. Then from B, we have B->JFK? But we already used B->JFK? Actually we used B->JFK? In this sequence, after A->B, we are at B. Then from B we take B->JFK. So we used B->JFK. Then at JFK we take JFK->B. But then from B we have no outgoing? But we have used all tickets? Let's list: used: JFK->A, A->B, B->JFK, JFK->B. That's all four. But after JFK->B, we are at B and have no more tickets. That's fine because we used all. So it works.
But what about a case where greedy gets stuck? Consider: JFK -> A, JFK -> B, A -> C, B -> A, C -> JFK. Lexical order: A < B. If we go JFK -> A, then A -> C, then C -> JFK, then at JFK we have only JFK -> B left, so we go JFK -> B, then from B we have B -> A, then from A we have no outgoing? But we have used all? Used: JFK->A, A->C, C->JFK, JFK->B, B->A. That's all 5? Actually there are 5 tickets? Wait list: JFK->A, JFK->B, A->C, B->A, C->JFK. That's 5. The sequence: JFK->A, A->C, C->JFK, JFK->B, B->A. That uses all. But after B->A, we are at A and no outgoing from A? But we have used all tickets, so it's fine. So it worked.
But consider: JFK -> A, JFK -> B, A -> B, B -> C, C -> JFK. Lexical: A < B. Greedy: JFK->A, then A->B, then B->C, then C->JFK, then JFK->B? But we have used JFK->A and A->B and B->C and C->JFK. That's 4 tickets. The fifth is JFK->B. After C->JFK, we are at JFK and take JFK->B. Then from B we have no outgoing? But we have used all? Actually we used all 5? Wait: tickets: JFK->A, JFK->B, A->B, B->C, C->JFK. That's 5. Sequence: JFK->A, A->B, B->C, C->JFK, JFK->B. That uses all. After JFK->B, we are at B and no more tickets. So it works.
But there is a known counterexample where greedy lexical order fails if we don't backtrack? Actually the standard solution using greedy DFS with backtracking (i.e., if we get stuck we backtrack) works but is exponential. However, the efficient solution using Hierholzer's algorithm by processing neighbors in lexical order and doing post-order DFS (pushing the node to the result when backtracking) yields the correct itinerary in reverse order. That algorithm doesn't get stuck because it processes edges in lexical order but does a DFS until it gets stuck (i.e., no more outgoing edges) and then backtracks, but it uses a multigraph (since multiple tickets can have same from-to) and we remove edges as we use them. The key is: we sort the adjacency lists in reverse lexical order? Actually to get the smallest lexical order, we need to visit the smallest lexical neighbor first? But in Hierholzer, we insert the node when we backtrack. So if we want the itinerary in forward order, we need to traverse in a way that the smallest lexical next airport is taken first? But careful: In Hierholzer's algorithm for Eulerian path, we do a DFS, and when we finish exploring from a node, we add it to the result. The result is in reverse order of the path. To get the forward itinerary, we reverse the result. But we want the smallest lexical itinerary. If we sort the adjacency list in reverse order (so that we pop the smallest from the end) or we sort normally and then iterate? Actually common implementation: for each node, we have a min-heap or sorted list of neighbors. We then repeatedly take the smallest neighbor (since we want lexical order), and remove that edge. But if we do a DFS that always takes the smallest available neighbor, we might get stuck? Actually Hierholzer's algorithm works regardless of the order of neighbors as long as we traverse all edges. But to get the smallest lexical itinerary, we need to ensure that when there is a choice, we take the smallest lexical next airport. However, the standard approach is: sort the adjacency list for each node in reverse lexical order (so that when we pop from the end, we get the smallest) or use a priority queue. But actually, if we do a DFS that always chooses the smallest neighbor, and then when we get stuck, we backtrack and push the node to the result, we end up with the Eulerian path in reverse order. But is that the smallest lexical? Not necessarily. Because the order in which we visit nodes affects the result. There is a known trick: if we sort the adjacency lists in lexical order, and then use a stack/recursion to traverse, we might not get the smallest lexical itinerary. Actually, the correct method to get the smallest lexical itinerary is to sort the adjacency lists in reverse lexical order and then do a DFS (like using a stack) so that we always take the smallest available neighbor first? Wait, let's think.
We want the itinerary such that the sequence of airports is lexicographically smallest. That means at the first point of difference, we want the smallest airport name. So we want to choose the smallest possible next airport at the earliest decision point. However, if we always choose the smallest next airport greedily without backtracking, we might get stuck. But Hierholzer's algorithm effectively does a greedy traversal that always takes the edge with the smallest lexical destination (by processing neighbors in order) but it only backtracks when no more edges are available. The trick is that we process neighbors in lexical order, but we use a stack/recursion and we push the current node to the result only after processing all its edges. That means that if there is a choice, we commit to the smallest neighbor, but if later we get stuck, we backtrack to the previous node and continue from there. However, in Hierholzer, we don't actually "backtrack" in the sense of trying a different choice at a node because we remove edges as we go. So if we start at JFK and take the smallest neighbor, we will eventually come back to JFK if there is an Eulerian circuit. But if it's a path (not circuit), we start at JFK and end somewhere else.
But consider the example from Leetcode:
Input: [["MUC","LHR"],["JFK","MUC"],["SFO","SJC"],["LHR","SFO"]]
Output: ["JFK","MUC","LHR","SFO","SFC"]? Actually SFO->SJC? Wait: tickets: MUC->LHR, JFK->MUC, SFO->SJC, LHR->SFO. So graph: JFK->MUC, MUC->LHR, LHR->SFO, SFO->SJC. That's a chain. Lexical order? JFK -> MUC is only one. So output: JFK, MUC, LHR, SFO, SJC.
Another example: [["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],["ATL","JFK"],["ATL","SFO"]]. What is the expected output? Lexical: from JFK we have ATL and SFO. ATL < SFO, so we first go to ATL? But then from ATL we have JFK and SFO. JFK < SFO, so go to JFK. Then from JFK we have SFO (since JFK->ATL already used? Actually we used JFK->ATL, so only JFK->SFO left). Then from SFO we have ATL. Then from ATL we have SFO (since ATL->JFK used? Actually we used ATL->JFK? In this sequence: JFK->ATL, ATL->JFK, JFK->SFO, SFO->ATL, then ATL->SFO. That uses all. Itinerary: JFK, ATL, JFK, SFO, ATL, SFO. But is that lexicographically smallest? Compare with if we first go JFK->SFO: JFK->SFO, then SFO->ATL, then ATL->JFK, then JFK->ATL, then ATL->SFO. That gives: JFK, SFO, ATL, JFK, ATL, SFO. Compare the two sequences: First difference at second element: ATL vs SFO. Since ATL < SFO, the first sequence is lexicographically smaller. So indeed taking the smallest neighbor first yields the smallest lexical itinerary.
But what if there is a situation where taking the smallest neighbor leads to a dead end before using all tickets? Then the greedy would fail. But Hierholzer's algorithm ensures that we don't get stuck because we only finish a node when it has no more edges. In the process, if we take an edge that leads to a node that later has no way to use all edges, we would eventually get stuck at that node, but then we backtrack? Actually in Hierholzer's algorithm, we don't backtrack in the sense of trying a different edge from a node because we consume edges as we traverse. If we take an edge and later get stuck, that means that the graph is not Eulerian? But the problem guarantees it is. So if we always take the smallest available neighbor, we will not get stuck prematurely because the graph has an Eulerian path. Wait, is that guaranteed? Not necessarily. Consider a graph that is Eulerian but the greedy choice of smallest neighbor might lead to a path that gets stuck before using all edges if we don't have the ability to backtrack? But Hierholzer's algorithm does not require backtracking because it uses a stack: when a node has multiple edges, we choose one and go deeper; if we later return to that node, we then take another edge. So it's not that we commit to a choice and never come back; we do come back if there are remaining edges. So the algorithm is: start at the starting node (JFK). While the current node has outgoing edges, choose the smallest lexical outgoing edge (by sorting adjacency lists), remove that edge, and move to the neighbor. When a node has no more outgoing edges, add it to the result and backtrack (pop from stack). This effectively does a DFS that prioritizes smallest lexical neighbor, and when we get stuck, we add the node to the result and go back to the previous node. This is exactly Hierholzer's algorithm for Eulerian path.
Thus, the greedy DFS approach (with recursion or stack) that processes neighbors in lexical order and uses all edges will produce the lexicographically smallest Eulerian path starting from JFK. The reason we need to process destinations in lexical order is to ensure that at each step, when there is a choice, we take the smallest lexical next airport, which leads to the smallest overall itinerary. If we processed in arbitrary order, we might get a valid itinerary but not necessarily the smallest lexical one.
How to handle dead ends? In this algorithm, we don't need to explicitly handle dead ends by backtracking in the sense of trying different permutations because the algorithm inherently handles it: when we reach a node with no outgoing edges, we add it to the result and backtrack to the previous node. Since we are using edges (removing them as we go), we will eventually use all edges. The "dead end" is actually a node that has no more edges, which is expected at the end of the Eulerian path. But note: if we get stuck at a node that still has unused edges somewhere else, that would mean the graph is not Eulerian? But the problem guarantees it is. However, in the process of DFS, we might reach a node that has no outgoing edges but there are still edges left elsewhere? That would be a problem. But Hierholzer's algorithm ensures that we only add a node to the result when it has no more edges, and we backtrack. If we have multiple components? But the graph is connected (since all tickets belong to one man and we start at JFK). So it's fine.
Implementation details:
We need to build an adjacency list: a dictionary mapping from airport to a list of destinations. But we need to be able to remove edges efficiently. Since we might have multiple tickets with same from-to, we need to account for duplicates. So we should store the destinations in a multiset. We can sort the list of destinations for each origin, but then we need to remove them one by one. We could use a list and pop from the front? But popping from front of a list is O(n). Better: we store the list in reverse lexical order (so that we can pop from the end in O(1)), or we use a min-heap (priority queue) but then we need to remove arbitrary? Actually we always remove the smallest. So if we sort the list in reverse order (largest first), then we can pop from the end to get the smallest. Example: for origin "JFK", destinations: ["ATL", "SFO"] -> sort in reverse: ["SFO", "ATL"], then we pop from the end: pop() gives "ATL". That is efficient.
Alternatively, we can use a deque and popleft? But if we sort in lexical order, then popleft gives smallest, but popleft from a list is O(n). So better to use a heap? But we need to be able to remove specific edges? Actually we only remove the smallest each time. So if we store a min-heap, we can heappop to get smallest. But we might have duplicates, so heap is fine. However, building a heap from a list is O(n log n) per node? Actually we can build a heap for each node's adjacency list. But then popping is O(log n). That is acceptable because total edges are up to 300 (in Leetcode constraints). But the problem doesn't specify constraints, but typically it's small. However, we can also use a list and sort it, then iterate with an index pointer. But we need to remove edges as we use them. If we use an index pointer, we can keep a pointer that moves forward. But then if we have multiple edges to the same destination? That's fine because we have multiple copies. So we can store the adjacency list as a multiset: we can use a Counter? But then we need to choose the smallest key with positive count. That would require scanning. Better: sort the list of destinations (with duplicates) and then use a pointer or stack.
The typical solution:
- Build graph: dict of from -> list of to.
- For each from, sort the list in reverse order (so that we can pop the smallest by popping from the end).
- Use a stack (or recursion) to perform DFS:
- Start at "JFK".
- While the current node has outgoing edges (i.e., the list is not empty):
- pop the smallest destination (from the end) from the current node's list.
- push the current node onto a stack? Actually the iterative Hierholzer:
stack = ["JFK"]
path = []
while stack:
while graph[stack[-1]]:
next_node = graph[stack[-1]].pop()
stack.append(next_node)
path.append(stack.pop())
Then reverse path? Actually in this version, path is built in reverse order: we push nodes when they have no more edges. So the final path is in reverse order. But wait: we start with stack containing "JFK". Then while the top of stack has outgoing edges, we go deeper. When a node has no outgoing edges, we pop it and add to path. That gives the path in reverse. So at the end, we reverse path to get the itinerary.
But careful: In this algorithm, we are not explicitly removing edges? We are popping from the adjacency list. That removes the edge. So it's correct.
Let's test with example:
graph:
JFK: [SFO, ATL] sorted reverse -> [SFO, ATL] (so pop gives ATL first? Actually if we sort reverse: descending order: SFO > ATL, so list is [SFO, ATL]. Then pop() from end gives ATL. So we take ATL first. That's the smallest? ATL is smaller than SFO? Actually lexical: ATL < SFO. So we want to take ATL first. So by sorting in reverse order and popping from the end, we get the smallest. Good.
So algorithm:
from collections import defaultdict
def findItinerary(tickets):
graph = defaultdict(list)
for a, b in tickets:
graph[a].append(b)
for key in graph:
graph[key].sort(reverse=True) # sort in descending order so that pop() gives smallest
stack = ["JFK"]
path = []
while stack:
while graph[stack[-1]]:
next_node = graph[stack[-1]].pop()
stack.append(next_node)
path.append(stack.pop())
return path[::-1]
But wait: is this correct for the example?
Example: [["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],["ATL","JFK"],["ATL","SFO"]]
graph:
JFK: ["SFO","ATL"] -> sort reverse: ["SFO","ATL"]? Actually alphabetical: ATL < SFO. So ascending: [ATL, SFO]. Reverse: [SFO, ATL].
ATL: ["JFK","SFO"] -> sort reverse: ["SFO","JFK"]? Actually alphabetical: JFK < SFO, so ascending: [JFK, SFO], reverse: [SFO, JFK].
SFO: ["ATL"] -> reverse: ["ATL"].
Now stack: ["JFK"]
while stack: top = "JFK", graph["JFK"] non-empty -> pop() gives "ATL". stack: ["JFK","ATL"]
top = "ATL", graph["ATL"] non-empty -> pop() gives "JFK"? Because graph["ATL"] is ["SFO","JFK"], pop() gives "JFK" (the last element). stack: ["JFK","ATL","JFK"]
top = "JFK", graph["JFK"] now has ["SFO"] (since we removed ATL). pop() gives "SFO". stack: ["JFK","ATL","JFK","SFO"]
top = "SFO", graph["SFO"] has ["ATL"], pop() gives "ATL". stack: ["JFK","ATL","JFK","SFO","ATL"]
top = "ATL", graph["ATL"] now has ["SFO"] (since we removed JFK). pop() gives "SFO". stack: ["JFK","ATL","JFK","SFO","ATL","SFO"]
top = "SFO", graph["SFO"] is empty. So we pop SFO and add to path: path = ["SFO"]
stack: ["JFK","ATL","JFK","SFO","ATL"]
top = "ATL", graph["ATL"] is empty (since we removed SFO). pop ATL -> path = ["SFO","ATL"]
stack: ["JFK","ATL","JFK","SFO"]
top = "SFO", graph["SFO"] empty -> pop SFO -> path = ["SFO","ATL","SFO"]
stack: ["JFK","ATL","JFK"]
top = "JFK", graph["JFK"] empty -> pop JFK -> path = ["SFO","ATL","SFO","JFK"]
stack: ["JFK","ATL"]
top = "ATL", graph["ATL"] empty -> pop ATL -> path = ["SFO","ATL","SFO","JFK","ATL"]
stack: ["JFK"]
top = "JFK", graph["JFK"] empty -> pop JFK -> path = ["SFO","ATL","SFO","JFK","ATL","JFK"]
reverse: ["JFK","ATL","JFK","SFO","ATL","SFO"] which is the expected itinerary.
That works.
But what about the case where there is a dead end that is not the final node? In Hierholzer, we only add a node to the path when it has no more edges. If we get stuck at a node that still has edges? That would mean we haven't removed all edges from that node? But we are removing edges as we go. So if a node has edges, we will take one. The only way we get stuck at a node is if it has no outgoing edges. But if there are still edges left in the graph, they must be in some other node that we haven't visited? But since the graph is connected and we are doing a DFS that covers all edges, we will eventually visit all edges. The algorithm is proven to work for any Eulerian path (or circuit). So we don't need to worry about dead ends in the sense of having to backtrack and try a different edge because the algorithm inherently uses all edges.
However, note: the above iterative algorithm uses a stack and while loop. But it might not work if we have multiple edges from the same node and we need to return to that node later? But Hierholzer's algorithm does exactly that: when we traverse from a node, we remove one edge and go to the neighbor. If later we come back to the same node (because some other path leads back), we will then take another edge if available. That's why we need to keep the adjacency list for each node and keep removing edges until empty. So the algorithm is correct.
But what about the requirement that we start at "JFK"? The problem says the man departs from "JFK". So we start at JFK. But is it guaranteed that the Eulerian path starts at JFK? Actually, for a directed Eulerian path, the start vertex has out-degree = in-degree + 1 (if it's not a circuit). But the problem says all tickets belong to a man who departs from JFK, so we assume that JFK is the starting airport. So we start at JFK.
Now, why is it important to process destinations in lexical order? Because we want the lexicographically smallest itinerary. If we process in arbitrary order, we might get a valid itinerary but not the smallest. For example, if from JFK we have two destinations: ATL and SFO. If we process SFO first, we might get an itinerary starting with JFK->SFO which is lexicographically larger than JFK->ATL. So we must choose the smallest lexical next airport when there is a choice.
But careful: even if we always choose the smallest next airport, we must ensure that we don't get stuck prematurely. The Hierholzer algorithm with lexical order processing guarantees that we get the smallest lexical Eulerian path? I think yes. There is a proof: by always taking the smallest lexical edge available, we ensure that the path is lexicographically smallest. Because if there were a smaller path, at the first point of difference, it would have a smaller airport, but we took the smallest possible at that step.
However, there is a nuance: what if taking the smallest edge leads to a situation where later we have to take a larger edge earlier, making the overall path larger? But since we are constructing an Eulerian path, the set of edges is fixed. The order in which we traverse edges from a node matters. If we take the smallest edge first, then the path from that node onward will be as small as possible given that we have to use all edges. But is it globally minimal? I believe it is. Actually, this is known: to get the lexicographically smallest Eulerian path, you sort the adjacency lists in reverse order and use Hierholzer. This is a standard solution.
So the answer to "why process destinations in lexical order?" is: to ensure the reconstructed itinerary is the lexicographically smallest among all possible valid itineraries.
How to handle the case where you get stuck in a dead end? In the context of Hierholzer's algorithm, we don't get stuck in a dead end that leaves unused edges because the algorithm traverses all edges. But if we were to implement a naive greedy DFS that always takes the smallest neighbor and if it leads to a dead end (no outgoing edges) but there are still unused tickets, we would need to backtrack and try the next smallest neighbor. That would be exponential. However, the Hierholzer algorithm avoids explicit backtracking by using a stack and processing edges in a way that we only get stuck at the very end (when all edges are used). So the "dead end" is actually the final node of the Eulerian path. So we handle it by adding that node to the itinerary and backtracking to the previous node.
But the question says: "How do you handle the case where you get stuck in a dead end?" Possibly they are referring to the naive DFS approach. So we should explain both: the greedy DFS with backtracking (which is correct but inefficient) and the efficient Hierholzer algorithm. But since the problem says "a greedy DFS approach is common", they might be expecting the backtracking approach? Actually many solutions use recursion with backtracking and sorting the adjacency list, and they mark edges as used. But that can be O(2^n) in worst case? But with sorting and pruning it might work for small input. However, the efficient solution is Hierholzer.
Given the context, I'll describe the Hierholzer algorithm as the greedy DFS approach (since it's DFS-like) and explain why we sort in reverse order and use a stack.
But the question: "A greedy DFS approach is common, and why is it important to process the destinations in lexical order? How do you handle the case where you get stuck in a dead end."
So I'll answer:
We model the problem as finding an Eulerian path in a directed multigraph starting from "JFK". Since we need the lexicographically smallest itinerary, we must always choose the smallest lexical destination when traversing. To achieve this efficiently, we use Hierholzer's algorithm for Eulerian path with a slight modification: for each departure airport, we sort its list of destination airports in reverse lexical order. Then we perform a DFS using a stack. We start from "JFK", and while the current airport has outgoing edges, we take the smallest lexical destination (by popping from the end of the sorted list) and push it onto the stack. When an airport has no more outgoing edges, we pop it from the stack and append it to the result. After the stack is empty, the result is in reverse order, so we reverse it to get the itinerary.
This approach handles the "dead end" naturally: when we reach an airport with no outgoing edges, it means we have used all tickets that originated from that airport, and it is part of the final path. We then backtrack to the previous airport and continue from there. Since the graph has an Eulerian path (guaranteed by the problem), we will eventually use all edges.
If we were to use a naive greedy DFS without backtracking (always taking the smallest neighbor and not being able to return to a node if we get stuck prematurely), we might get stuck in a dead end before using all tickets. But the Hierholzer algorithm avoids that by allowing us to return to a node later if it still has unused edges.
Thus, the key points:
- Process destinations in lexical order to ensure the smallest lexical itinerary.
- Use Hierholzer's algorithm (DFS with stack) to efficiently traverse all edges without getting stuck prematurely.
I'll write the function accordingly.
Let's code it.
Note: We need to handle the case where a airport does not appear in the graph as a key (i.e., no outgoing edges). So when we check graph[stack[-1]], if the airport is not in the dict, we should treat it as an empty list. So we can use defaultdict(list) which returns empty list for missing keys.
But careful: When we pop from stack and then check graph[stack[-1]]? Actually in the while loop, we check while graph[stack[-1]]: but if stack[-1] is not in graph, then graph[stack[-1]] is [] (from defaultdict), so the condition is false. That's fine.
But what about when we pop from stack and then the next top might be an airport that is not in graph? That's fine because we'll just pop it and add to path.
So implementation:
from collections import defaultdict
def findItinerary(tickets):
graph = defaultdict(list)
for a, b in tickets:
graph[a].append(b)
for key in graph:
graph[key].sort(reverse=True) # sort in descending order so that pop() gives smallest
stack = ["JFK"]
path = []
while stack:
# If the current airport has outgoing edges, push the next airport onto stack.
# Otherwise, pop and add to path.
while graph[stack[-1]]:
next_node = graph[stack[-1]].pop()
stack.append(next_node)
path.append(stack.pop())
return path[::-1]
But wait: in the inner while, we are checking graph[stack[-1]] repeatedly. But after we pop an edge, the current top might change? Actually the inner while is: while the current top (stack[-1]) has outgoing edges, we take one and push the neighbor. Then we check again with the new top. That's correct.
But there is a nuance: when we push a new node, we then check that new node's outgoing edges. So it's a DFS.
Test with simple chain: JFK->MUC->LHR->SFO->SJC.
graph: JFK: [MUC], MUC: [LHR], LHR: [SFO], SFO: [SJC]. All sorted reverse same.
stack: ["JFK"]
while stack: top JFK has [MUC] -> pop -> push MUC. stack: ["JFK","MUC"]
top MUC has [LHR] -> pop -> push LHR. stack: ["JFK","MUC","LHR"]
top LHR has [SFO] -> pop -> push SFO. stack: ["JFK","MUC","LHR","SFO"]
top SFO has [SJC] -> pop -> push SJC. stack: ["JFK","MUC","LHR","SFO","SJC"]
top SJC has no outgoing (graph["SJC"] is [] because not in graph? Actually we have no ticket from SJC, so graph["SJC"] is [] (from defaultdict). So we pop SJC -> path = ["SJC"]
stack: ["JFK","MUC","LHR","SFO"]
top SFO now has [] (since we removed SJC) -> pop SFO -> path = ["SJC","SFO"]
top LHR has [] -> pop -> path = ["SJC","SFO","LHR"]
top MUC has [] -> pop -> path = ["SJC","SFO","LHR","MUC"]
top JFK has [] -> pop -> path = ["SJC","SFO","LHR","MUC","JFK"]
reverse -> ["JFK","MUC","LHR","SFO","SJC"] correct.
So it works.
But note: we are popping from the adjacency list, so we are removing edges. This is important.
Now, about the dead end: In this algorithm, we only get stuck when a node has no outgoing edges. That is the dead end. But since we are using all edges, that dead end is actually the last airport in the itinerary (or one of the last if it's a circuit). We handle it by popping it and adding to path, then backtracking.
So to answer: "How do you handle the case where you get stuck in a dead end?" We handle it by naturally incorporating it into Hierholzer's algorithm: when we reach a node with no remaining outgoing edges, we add it to the result and backtrack to the previous node. This ensures that we only consider a node as part of the final path when we have exhausted all its outgoing edges. Since the graph has an Eulerian path, we will not leave any edge unused.
If we were using a simple recursive DFS that builds the path as we go and tries to use all tickets, we would need to backtrack when we get stuck before using all tickets. That would involve removing the last airport and trying a different neighbor. But that is inefficient. The Hierholzer algorithm avoids explicit backtracking by the stack mechanism.
Thus, the efficient greedy DFS (Hierholzer) handles dead ends implicitly.
Now, the function:
We'll write it as:
def findItinerary(tickets):
from collections import defaultdict
graph = defaultdict(list)
for a, b in tickets:
graph[a].append(b)
for key in graph:
graph[key].sort(reverse=True) # sort in descending order
stack = ["JFK"]
path = []
while stack:
while graph[stack[-1]]:
next_node = graph[stack[-1]].pop()
stack.append(next_node)
path.append(stack.pop())
return path[::-1]
But wait: what if there are multiple edges between same pair? We are storing a list and popping. That works because we have multiple entries.
Edge case: if tickets is empty? Then graph is empty. stack starts with "JFK". Then graph["JFK"] is [] (since not in graph? Actually if no tickets, graph is empty dict. But we use defaultdict, so graph["JFK"] returns [] (since key not present, defaultdict creates empty list? Actually defaultdict(list) will create an empty list when accessing a missing key. So graph["JFK"] is []. So the inner while is false. Then we pop stack -> path = ["JFK"]. Then stack empty. Return ["JFK"]. That seems correct: if no tickets, the itinerary is just ["JFK"]? But the problem says we have a list of tickets, so probably at least one ticket. But it's fine.
Another edge: what if there is a ticket from an airport that never appears as origin in the list? That airport will not be in graph as a key, but that's fine because we only traverse from origins that have outgoing edges.
Now, about the lexical order: we sorted each adjacency list in reverse order so that pop() gives the smallest. That is because when we pop from the end, we get the last element, which is the smallest if sorted ascending? Actually if we sort in ascending order: [ATL, SFO], then pop() from the end gives SFO (the largest). So we want to pop the smallest, so we sort in descending order: [SFO, ATL], then pop() gives ATL. Alternatively, we can sort in ascending order and then pop from the front (using pop(0)) but that is O(n). So sorting in reverse and popping from end is efficient.
Thus, the answer.
Now, the user asked: "You are given a list of airline tickets represented by [from, to] pairs. All of the tickets belong to a man who departs from "JFK". Reconstruct the man's itinerary in order. Please this is the "Reconstruct Itinerary" problem, this can be modeled as finding a specific path in a graph, write a function that solves this problem. A greedy DFS approach is common, and why is it important to process the destinations in lexical order? How do you handle the case where you get stuck in a dead end."
So I should provide a clear explanation and the function.
I'll write an answer that includes:
- Modeling as Eulerian path.
- Explanation of greedy DFS (Hierholzer) with sorting.
- Why lexical order: to get the smallest lexical itinerary.
- Handling dead ends: by using stack and adding nodes to path only when they have no more outgoing edges; this naturally handles dead ends as part of the Eulerian path.
And then provide the code.
But note: there is also a recursive version. But I'll provide the iterative one.
Let me also consider if the problem expects the function to return the itinerary as a list of strings.
Yes.
So final answer.
To solve the "Reconstruct Itinerary" problem, we model the tickets as a directed multigraph where each ticket is an edge from from to to. The goal is to find an Eulerian path (a path that uses every edge exactly once) starting from "JFK" that is lexicographically smallest when read as a sequence of airport codes.
Why Process Destinations in Lexical Order?
Since we need the smallest lexical itinerary, at each airport we must choose the smallest possible next destination if multiple options exist. Processing destinations in lexical order ensures that the first differing airport in the itinerary is as small as possible, leading to the overall smallest sequence.
Handling Dead Ends with Hierholzer's Algorithm
A naive greedy DFS that always picks the smallest neighbor might get stuck in a dead end (no outgoing edges) before using all tickets, requiring backtracking and becoming inefficient. Instead, we use Hierholzer’s algorithm for Eulerian paths, modified to prioritize lexical order:
- Build an adjacency list where each origin maps to a list of destinations.
- Sort each origin’s list in reverse lexical order so we can
pop() the smallest destination in O(1) time.
- Use a stack to simulate DFS:
- Start at "JFK".
- While the current airport has outgoing edges, push the smallest destination onto the stack and remove that edge.
- When an airport has no more edges, pop it from the stack and append it to the result path.
- The result is built in reverse order; reverse it at the end.
This algorithm naturally handles "dead ends": an airport is added to the path only when all its outgoing edges are exhausted. Since the graph has an Eulerian path (guaranteed by the problem), we never truly get stuck prematurely—every dead end is actually the correct next airport in the final itinerary.
Complexity
- Time: O(E log E) due to sorting each adjacency list (E = number of tickets). The DFS traversal is O(E).
- Space: O(E) for the graph, stack, and path.
Code Implementation
from collections import defaultdict
def findItinerary(tickets):
"""
Reconstruct the itinerary from a list of airline tickets.
Each ticket is [from, to]. The itinerary must start at "JFK" and use all tickets once.
Returns the lexicographically smallest itinerary.
"""
# Build graph: from -> list of destinations
graph = defaultdict(list)
for a, b in tickets:
graph[a].append(b)
# Sort each list in reverse order so pop() gives smallest lexical destination
for key in graph:
graph[key].sort(reverse=True)
stack = ["JFK"]
path = []
while stack:
# While current airport has outgoing edges, traverse the smallest one
while graph[stack[-1]]:
next_node = graph[stack[-1]].pop()
stack.append(next_node)
# No more edges from current airport: add to path and backtrack
path.append(stack.pop())
# Reverse to get forward itinerary
return path[::-1]
Example
tickets = [["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],["ATL","JFK"],["ATL","SFO"]]
print(findItinerary(tickets))
# Output: ['JFK', 'ATL', 'JFK', 'SFO', 'ATL', 'SFO']
This solution efficiently produces the lexicographically smallest Eulerian path starting from "JFK" without explicit backtracking, handling all edge cases including duplicate tickets.