Hierholzer with min-heaps
Time O(E log E) Space O(E)Map each airport to a PriorityQueue of destinations. DFS: while the queue isn't empty, poll and recurse; then add the airport to the front of the route.
tickets = [[MUC,LHR],[JFK,MUC],[SFO,SJC],[LHR,SFO]]route(list)
empty
Step 1/4Each airport keeps its destinations in a min-heap (alphabetical). Start at JFK.
import java.util.*;
class Solution {
private final Map<String, PriorityQueue<String>> g = new HashMap<>();
private final LinkedList<String> route = new LinkedList<>();
public List<String> findItinerary(List<List<String>> tickets) {
for (List<String> t : tickets) g.computeIfAbsent(t.get(0), k -> new PriorityQueue<>()).add(t.get(1));
visit("JFK");
return route;
}
private void visit(String airport) {
PriorityQueue<String> next = g.get(airport);
while (next != null && !next.isEmpty()) visit(next.poll());
route.addFirst(airport);
}
}Verdict: Dead ends are appended first, so they end up last.