โ† Wiki Index / Computation & Algorithms / Hierholzer's Algorithm
๐Ÿ’ป Computation & Algorithms

Hierholzer's Algorithm

Hierholzer's algorithm constructs an Eulerian circuit or Eulerian trail in a connected undirected or directed multigraph in optimal O(E) linear time by splicing edge-disjoint cycles via a traversal stack.

Hierholzer's algorithm is a linear-time O(E) graph algorithm in computation and algorithms that constructs an Eulerian circuit (or Eulerian trail) in a connected undirected or directed multigraphโ€”a closed walk (or open walk) that traverses every edge of the graph once and only once. Formulated by German mathematician Carl Hierholzer shortly before his death in 1871 and published posthumously by his colleagues in Mathematische Annalen in 1873, the paper provided the first rigorous converse to Leonhard Euler's 1736 solution of the Seven Bridges of Kรถnigsberg problem, proving that degree parity and connectivity are both necessary and sufficient for the existence of an Eulerian circuit.

Within computational complexity theory and modern algorithmic bioinformatics, Hierholzer's algorithm is the standard linear-time procedure for Eulerian tour construction. Unlike Fleury's algorithm (1883), which must test at every step whether a candidate edge is a graph bridge in O(E2) or O(E log2 V) time, Hierholzer's algorithm greedily follows unused edges to close simple cycles and splices detour sub-cycles into the main tour via a stack in O(V + E) optimal time. This capability underpins shotgun genome assembly over De Bruijn graphs as well as route inspection and VLSI layout synthesis.

Mathematical Formulation and Euler's Degree Conditions

Eulerian Circuits and Trails in Undirected and Directed Multigraphs

Let G = (V, E) be a finite multigraph (allowing parallel edges and self-loops) with vertex count V = |V| and edge count E = |E|.

  • An Eulerian trail (or Eulerian path) is a walk in G that traverses every edge e โˆˆ E once.
  • An Eulerian circuit (or Eulerian tour / Eulerian cycle) is a closed Eulerian trail that starts and ends at the same vertex.
  • A graph is Eulerian if it possesses an Eulerian circuit, and semi-Eulerian if it possesses an Eulerian trail that is not closed.

Assuming all vertices of nonzero degree belong to a single connected component (in the undirected case) or a single strongly connected component (in the directed case, with weak connectivity for semi-Eulerian trails), the Eulerโ€“Hierholzer Theorem characterizes existence completely via local vertex degrees:

  1. Undirected Multigraphs:
    • G has an Eulerian circuit if and only if every vertex v โˆˆ V has even degree (deg(v) โ‰ก 0 mod 2).
    • G has an open Eulerian trail between s and t (s โ‰  t) if and only if s and t have odd degree and every other vertex v โˆˆ V \ {s, t} has even degree.
  2. Directed Multigraphs:
    • G has a directed Eulerian circuit if and only if every vertex v โˆˆ V is balanced, meaning its in-degree equals its out-degree: degโˆ’(v) = deg+(v).
    • G has a directed Eulerian trail from s to t (s โ‰  t) if and only if deg+(s) โˆ’ degโˆ’(s) = 1, degโˆ’(t) โˆ’ deg+(t) = 1, and degโˆ’(v) = deg+(v) for all v โˆˆ V \ {s, t}.

Cycle Decomposition and the Splicing Invariant

Hierholzer's constructive proof rests on the Degree-Parity Preservation Lemma: in any graph where every vertex has even degree (or balanced in-degree and out-degree), any maximal walk that starts at a vertex v0 and repeatedly traverses previously unused edges without repeating any edge cannot get stuck at any vertex other than v0.

Proof: Whenever the walk enters an intermediate vertex u โ‰  v0 along an unused incoming edge, it consumes 1 unit of u's remaining degree (or 1 unit of in-degree). Because u began with an even degree (or equal in-degree and out-degree) and each previous pass through u consumed pairs of one incoming and one outgoing edge, at least one unused outgoing edge incident to u must remain available. Thus the walk can only terminate when it returns to the starting vertex v0, forming a closed cycle C1.

Removing the edges of C1 from G leaves a residual subgraph Gโ€ฒ = (V, E \ E(C1)) in which every vertex still has even degree (or balanced in/out-degree) because C1 removed an equal number of incoming and outgoing edges at every vertex it visited. If E \ E(C1) โ‰  โˆ…, connectivity of G guarantees that at least one vertex w visited by C1 still has unused incident edges in Gโ€ฒ. Launching a second greedy walk from w in Gโ€ฒ closes a second edge-disjoint cycle C2, which can be spliced directly into C1 at w to form a longer closed walk. Repeating until all E edges are exhausted yields a complete Eulerian circuit.

Algorithmic Procedure and Complexity Analysis

Stack-Based Post-Order Cycle Splicing

Rather than maintaining linked lists to splice sub-cycles explicitly, modern implementations of Hierholzer's algorithm use a single traversal stack S and an output list L alongside current-arc pointers (identical to the pointer-advance technique in Dinic's algorithm):

  1. Initialization: Push the starting vertex v0 onto the active stack S = [v0], and initialize an empty circuit list L = []. (If computing an open Eulerian trail from odd/excess vertex s to t, either start at s or temporarily add a virtual edge (t, s) to close the circuit and split the output tour at (t, s) upon completion.)
  2. Stack Loop: While S is nonempty, inspect the vertex u = top(S):
    • Advance Along Unused Edge: If u has an unused outgoing incident edge e = (u, v) (found in O(1) amortized time by advancing u's adjacency pointer past any already deleted edges), mark e as used/deleted and push v onto S.
    • Retreat and Output (Splicing): If u has no remaining unused incident edges, pop u from S and append u to the output list L.
  3. Finalization: Reverse L (for directed graphs) to obtain the ordered sequence of E + 1 vertices forming the Eulerian circuit.

Why Stack Popping Automatically Splices Cycles in O(E) Time

When the initial greedy walk closes a cycle C1 back to v0 and v0 has no remaining unused edges, the algorithm pops vertices from the end of C1 onto L until it backtracks to the last vertex w on C1 that still possesses unused incident edges. Before popping w or any prefix of C1 preceding w, the stack grows from w to trace out the entire detour sub-cycle C2 (and any nested sub-cycles inside C2) and pops all of C2 into L before resuming the pop of the prefix of C1. Because each edge e โˆˆ E is pushed onto S once and popped from S once, both time and space complexity are strictly O(V + E).

Comparison of Eulerian and Route-Inspection Algorithms

Algorithm / ProblemGraph & Edge ConstraintsWorst-Case Time ComplexityCore Algorithmic Mechanism
Hierholzer's Algorithm (1873)Eulerian Directed or UndirectedO(V + E)Greedy cycle walking + stack post-order splicing
Fleury's Algorithm (1883)Eulerian Undirected / DirectedO(E2) (or O(E log2 V))Avoids cutting bridges via Tarjan bridge-finding
BEST Theorem Counting (1941โ€“1951)Count all directed Eulerian toursO(V3)Matrix-Tree determinant ร— โˆ (deg+(v) โˆ’ 1)!
Undirected Chinese Postman (Edmonds & Johnson 1973)General Connected UndirectedO(V3)All-pairs shortest paths + weighted blossom algorithm + Hierholzer
Directed Chinese Postman (Edmonds & Johnson 1973)General Strongly Connected DirectedO(V E + V2 log V)Min-cost flow (via Hungarian algorithm / Dijkstra's algorithm) + Hierholzer

Scientific and Engineering Applications

  1. De Novo Genome Assembly via De Bruijn Graphs (Pevzner, Tang, and Waterman, 2001): Instead of formulating shotgun DNA sequence assembly as an NP-hard Hamiltonian path problem on an overlap graph, Eulerian assemblers (EULER, SPAdes, Velvet) break sequencing reads into (k โˆ’ 1)-mer vertices and k-mer directed edges in a De Bruijn graph, reconstructing genomic contigs as Eulerian trails via Hierholzer's algorithm.
  2. De Bruijn Sequence Generation and Combinatorial Gray Codes: Constructing a cyclic sequence of length ฯƒk over an alphabet of size ฯƒ containing every possible length-k substring once reduces to running Hierholzer's algorithm on the ฯƒ-ary De Bruijn graph on ฯƒkโˆ’1 vertices.
  3. CMOS VLSI Standard-Cell Layout (Euler Path Gate Chaining): In complementary metal-oxide-semiconductor (CMOS) physical design, pull-up PMOS and pull-down NMOS transistor dual graphs are chained into contiguous diffusion strips without isolation breaks by finding common Eulerian trails across the series-parallel dual multigraphs.

Frequently Asked Questions

Why is Hierholzer's algorithm preferred over Fleury's algorithm?

Fleury's algorithm requires checking at every vertex whether a candidate edge is a bridge of the remaining graph (an edge whose removal disconnects the remaining non-isolated vertices). Testing bridge status via DFS at each of the E steps takes O(E2) time (or O(E log2 V) using dynamic graph connectivity structures), whereas Hierholzer's algorithm requires zero connectivity queries during traversal and runs in O(V + E) time.

How does Hierholzer's algorithm handle graphs with parallel edges in an undirected representation?

In an undirected multigraph, each edge e = {u, v} is assigned a unique edge index id โˆˆ {0, โ€ฆ, E โˆ’ 1} stored alongside both endpoints' adjacency lists, and a boolean array *used*[id] ensures that traversing e from u to v immediately marks its reverse entry at v as used in O(1) time.

References

  1. Hierholzer, C., & Wiener, C. (1873). "Ueber die Mรถglichkeit, einen Linienzug ohne Wiederholung und ohne Unterbrechung zu umfahren." Mathematische Annalen, 6(1), 30โ€“32. https://doi.org/10.1007/BF01442866
  2. Euler, L. (1741). "Solutio problematis ad geometriam situs pertinentis." Commentarii Academiae Scientiarum Petropolitanae, 8, 128โ€“140. https://doi.org/10.5479/sil.318525.39088000877480
  3. Edmonds, J., & Johnson, E. L. (1973). "Matching, Euler tours and the Chinese postman." Mathematical Programming, 5(1), 88โ€“124. https://doi.org/10.1007/BF01580113
  4. Pevzner, P. A., Tang, H., & Waterman, M. S. (2001). "An Eulerian path approach to DNA fragment assembly." Proceedings of the National Academy of Sciences, 98(17), 9748โ€“9753. https://doi.org/10.1073/pnas.171285098
๐Ÿงฌ Support Open Science
Explore interactive science games on LowKey Games or browse scientific apparel & accessories in the CRV Science Shop.
๐Ÿ’ก Spot an inaccuracy or have primary literature to expand this article?
Submit a citation or revision note using your shared CRV Science / LowKey Games profile ID.
Suggest Revision