Problems > One Stroke, Every Street > Editorial

One Stroke, Every Street — Solution & Editorial

Back to the Problem

Hierholzer's algorithm: walk greedily marking edges used, pushing vertices on a stack; when a vertex has no unused edges left, pop it into the answer. The reversed pop order is an Eulerian circuit. Implement it iteratively with a per-vertex pointer into the adjacency list so every edge is scanned O(1) times.

Complexity: O(N + M)

Watch out: A recursive DFS overflows the stack at M = 105; keep per-vertex adjacency pointers or the walk degrades to O(N·M).