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.

1 variation · 1 problem

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

Eulerian Path (Hierholzer)
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;
}

The variations

  1. 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.
Next: Candidate elimination: one pass to rule people out →

Mark it done once you can write the template from memory and you have solved the worked examples yourself.