Graphs · Pattern 10 of 14
Eulerian path: use every edge once (Hierholzer's algorithm)
Walk along unused edges until you get stuck, then back up. Each node you back out of goes at the front of the route. Reversed, that finish order uses every edge exactly once.
Watch the lesson
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
When to use it
- Use every ticket, edge or domino exactly once
- Reconstruct a route from its pieces
- Smallest lexical order among valid routes
The template
List<String> findItinerary(List<List<String>> tickets) {
Map<String, PriorityQueue<String>> adj = new HashMap<>(); // smallest destination first
for (List<String> t : tickets) adj.computeIfAbsent(t.get(0), k -> new PriorityQueue<>()).offer(t.get(1));
LinkedList<String> route = new LinkedList<>();
Deque<String> st = new ArrayDeque<>(List.of("JFK"));
while (!st.isEmpty()) {
PriorityQueue<String> out = adj.get(st.peek());
if (out != null && !out.isEmpty()) st.push(out.poll()); // take an unused ticket
else route.addFirst(st.pop()); // stuck: this airport comes last
}
return route;
} from collections import defaultdict
def find_itinerary(tickets):
adj = defaultdict(list)
for a, b in sorted(tickets, reverse=True):
adj[a].append(b) # reverse-sorted, so pop() gives the smallest
route, st = [], ["JFK"]
while st:
if adj[st[-1]]:
st.append(adj[st[-1]].pop()) # take an unused ticket
else:
route.append(st.pop()) # stuck: this airport comes last
return route[::-1] vector<string> findItinerary(vector<vector<string>>& tickets) {
unordered_map<string, priority_queue<string, vector<string>, greater<>>> adj; // smallest first
for (auto& t : tickets) adj[t[0]].push(t[1]);
vector<string> route, st = {"JFK"};
while (!st.empty()) {
auto& out = adj[st.back()];
if (!out.empty()) { string next = out.top(); out.pop(); st.push_back(next); } // unused ticket
else { route.push_back(st.back()); st.pop_back(); } // stuck
}
reverse(route.begin(), route.end());
return route;
} function findItinerary(tickets) {
const adj = new Map();
const sorted = [...tickets].sort((x, y) => (x[1] < y[1] ? 1 : x[1] > y[1] ? -1 : 0));
for (const [a, b] of sorted) {
if (!adj.has(a)) adj.set(a, []);
adj.get(a).push(b); // reverse-sorted, so pop() gives the smallest
}
const route = [], st = ['JFK'];
while (st.length) {
const out = adj.get(st[st.length - 1]);
if (out && out.length) st.push(out.pop()); // take an unused ticket
else route.push(st.pop()); // stuck: this airport comes last
}
return route.reverse();
} The variations
-
1Hierholzer with the smallest edge first
Keep each airport's destinations sorted and always take the smallest unused one. When an airport has no tickets left, it is the end of what remains, so add it to the route. Reverse the route at the end.
Mistakes to avoid
- Greedily taking the smallest destination and never backing up: it can run into a dead end with tickets left over. Adding a node only when it is stuck fixes that.
- Adding nodes to the route when you first visit them instead of when you leave them for good.
Mark it done once you can write the template from memory and you have solved the worked examples yourself.