Simple Algorithm
Algorithms & Data Structures · Optimal · 26 min

Euler Tours & Hamiltonian Paths

Hierholzer’s linear-time algorithm, and its NP-hard cousin.

In 1736 Euler proved that no walk through Königsberg crosses each of its seven bridges exactly once, without trying a single route: he counted the bridges at each land mass. The same parity count, made constructive by Hierholzer, finds a walk through every edge of any graph in linear time. Ask instead for a walk through every vertex exactly once, and no polynomial-time algorithm is known.

What you’ll learn

  • State and prove Euler's theorem for circuits and trails, in undirected and directed graphs.
  • Implement Hierholzer's algorithm in O(n+m)O(n + m), explain why it is correct, and contrast it with Fleury's bridge-avoiding rule.
  • Build de Bruijn sequences and assemble genomes as Eulerian paths in de Bruijn graphs, and solve the Chinese postman problem with a matching.
  • Explain why Hamiltonian cycles are NP-complete, decide them in O(2nn2)O(2^n n^2) time with Held–Karp, and prove Ore's sufficient condition.

Euler’s theorem

DerivationProof (undirected; the directed case pairs in-edges with out-edges)
  1. Necessity. Each time a trail passes through a vertex it uses two of its edges, one to arrive and one to leave. Only the two ends of an open trail are left with one unpaired edge, so every degree is even for a circuit, and exactly the two ends have odd degree for an open trail.

  2. edges of w used so far  =  2k−1  <  deg⁡(w)\text{edges of } w \text{ used so far} \;=\; 2k - 1 \;<\; \deg(w)

    A walk gets stuck only where it started. Let every degree be even and walk from vv along unused edges. On its kk-th arrival at a vertex w≠vw \ne v, the walk has used an odd number of ww's edges, so an unused one remains; the walk can only stop at vv, after closing a circuit CC:

  3. C=(…,u,… ) ⟶ (…,u,…,u⏟C′,… )C = (\dots, u, \dots) \ \longrightarrow\ (\dots, \underbrace{u, \dots, u}_{C'}, \dots)

    Splice. If CC misses some edges, connectivity gives a vertex uu on CC with an unused edge. Removing CC's edges subtracts an even number from every degree, so all remaining degrees are even; walk from uu to get a closed trail C′C' through uu, and insert it into CC at uu. Each splice uses new edges, so the process ends with every edge used:

  4. Open trails. With exactly two odd vertices aa and bb, add an edge abab. Now every degree is even, so there is an Eulerian circuit; deleting the added edge from it leaves an Eulerian trail from aa to bb. (By the handshake lemma, the number of odd vertices is always even.)

Predict before you look

Königsberg's four land masses touched 5, 3, 3 and 3 bridges. What is the smallest number of new bridges that would allow a walk crossing every bridge exactly once and returning to where it started?

Show the answer

2 bridges

A closed walk needs every land mass to touch an even number of bridges. A new bridge changes the parity of exactly two land masses, so four odd ones need at least two new bridges, and two suffice: pair the odd land masses up, say the island with one bank and the other two land masses with each other. A single new bridge would leave two odd land masses: enough for a walk that crosses every bridge once, but not for one that returns.

Hierholzer’s algorithm in linear time

The proof is an algorithm. Hierholzer's algorithm, published in 1873 after Hierholzer's death, performs the splicing without ever editing a list. Keep the current walk on a stack. If the vertex on top still has an unused edge, follow it and push the other end; otherwise pop the vertex and append it to the output. The output, reversed, is the Eulerian circuit or trail.

python
def euler_walk(n, edges, start, directed=False):
    """Hierholzer's algorithm. Call it from a valid start (see the degree conditions).
    Returns the vertices of an Eulerian circuit or trail, or None if some edge is unreachable."""
    adj = [[] for _ in range(n)]
    for i, (u, v) in enumerate(edges):
        adj[u].append((v, i))
        if not directed:
            adj[v].append((u, i))
    used = [False] * len(edges)
    nxt = [0] * n                          # next unexamined edge at each vertex
    stack, walk = [start], []
    while stack:
        u = stack[-1]
        while nxt[u] < len(adj[u]) and used[adj[u][nxt[u]][1]]:
            nxt[u] += 1                    # skip edges already walked from the other end
        if nxt[u] == len(adj[u]):
            walk.append(stack.pop())       # u is stuck: its place in the walk is final
        else:
            v, i = adj[u][nxt[u]]
            used[i] = True
            stack.append(v)
    walk.reverse()
    return walk if len(walk) == len(edges) + 1 else None

Each edge is followed once, and each pointer nxt[u] only moves forward through uu's list, so the time is O(n+m)O(n + m). Check the degree conditions first, then start anywhere for a circuit, or at the odd vertex (directed: the vertex with one extra out-edge) for a trail; the length test catches edges in another component. Tested on thousands of random Eulerian graphs, directed and undirected.

DerivationWhy the output is an Eulerian circuit
  1. stack=(x0=start, x1, …, xk),xi−1xi unused when pushed\text{stack} = (x_0 = \text{start},\ x_1,\ \dots,\ x_k),\qquad x_{i-1} x_i \text{ unused when pushed}

    The stack is always a trail from the start, since every push follows an unused edge, and every edge is used exactly once over the whole run. A vertex is popped only when all of its edges are used.

  2. Detours are output before the vertex they hang from. The first walk gets stuck back at the start (in the circuit case), exactly as in the proof. While popping, the search may reach a vertex pp that still has unused edges; the unused edges have even degrees, so the new walk from pp is a closed detour that returns to pp. Its vertices are popped, and output, before pp itself, so in the reversed output the detour sits exactly at pp: the splice of the proof.

  3. Consecutive outputs are adjacent. The vertex output right after uu is the vertex pp that lay below uu on the stack, either at once or at the end of a detour that returns to pp, and the edge that pushed uu joins them. Every edge is pushed exactly once, so the reversed output is a walk that uses every edge exactly once.

Think first A contest asks for the Eulerian trail from a given start whose vertex sequence is lexicographically smallest, as in reconstructing a travel itinerary from used tickets. What changes in the code?

Only the order of the adjacency lists: sort each one so that the smallest neighbor is tried first. With that order, the stack version outputs exactly the lexicographically smallest Eulerian trail from the start, a standard contest fact; we also checked it against brute force on thousands of small random graphs, directed and undirected. Greedily walking to the smallest neighbor without the stack fails, because it can strand edges behind it.

De Bruijn sequences, genomes and the postman

A de Bruijn sequence of order nn over kk symbols is a cyclic sequence of length knk^n in which every string of length nn appears exactly once as a window. Build the de Bruijn graph: one vertex per string of length n−1n - 1, and for each string x1…xnx_1 \dots x_n an edge from x1…xn−1x_1 \dots x_{n-1} to x2…xnx_2 \dots x_n. Every vertex has kk edges in and kk out, and any vertex reaches any other by shifting in its symbols, so by Euler's theorem the graph has an Eulerian circuit; the last symbols of its edges spell a de Bruijn sequence.

python
from itertools import product

def de_bruijn(k, n):
    """A cyclic sequence over 0..k-1 containing every length-n string exactly once (n >= 2)."""
    nodes = list(product(range(k), repeat=n - 1))
    index = {v: i for i, v in enumerate(nodes)}
    edges = [(index[w[:-1]], index[w[1:]]) for w in product(range(k), repeat=n)]
    walk = euler_walk(len(nodes), edges, start=0, directed=True)
    return [nodes[v][-1] for v in walk[1:]]      # the symbol each edge appends

With euler_walk from the previous step. For k=2k = 2 and n=3n = 3 it returns 01011100, a rotation of the classic 00010111: read cyclically, its eight windows 010, 101, 011, 111, 110, 100, 000 and 001 are all eight 3-bit strings. A keypad that checks only the last 4 digits typed is opened by some de Bruijn sequence of 104+3=10,00310^4 + 3 = 10{,}003 key presses, instead of 40,000 for typing every code separately.

Genome assembly. A sequencer reads millions of short fragments of a genome. Cut every read into its substrings of length kk, its kk-mers, and make one vertex per (k−1)(k - 1)-mer and one edge per kk-mer, from its prefix to its suffix: the genome spells an Eulerian path of this de Bruijn graph, which Hierholzer's algorithm finds in linear time (Idury & Waterman, 1995; Pevzner, Tang & Waterman, 2001). The older formulation, a path through every read of an overlap graph, asks for a Hamiltonian path instead, an NP-hard problem.

The Chinese postman. A postman must walk every street at least once and return, as cheaply as possible (Kwan Mei-Ko, 1960). If every degree is even, an Eulerian circuit costs exactly the total street length. Otherwise some streets are walked twice, and the cheapest repetitions pair up the odd-degree vertices: compute shortest-path distances between them, find a minimum-weight perfect matching of the odd vertices, and duplicate each matched pair's shortest path. With Edmonds's matching algorithm this takes polynomial time (Edmonds & Johnson, 1973). On a square of four streets of length 1 with one diagonal of length 2, the two odd corners are 2 apart, so the best tour costs 6+2=86 + 2 = 8. The directed version reduces to minimum-cost flow, but with both one-way and two-way streets the problem is NP-hard (Papadimitriou, 1976).

Hamiltonian paths: the hard cousin

A Hamiltonian path visits every vertex exactly once, and a Hamiltonian cycle also returns to its start. The problems look like Euler's, but no local test like the degree condition is known, and deciding whether a Hamiltonian cycle exists is NP-complete for directed and undirected graphs (Karp, 1972; see A Gallery of NP-Completeness Reductions). A polynomial-time algorithm would prove P = NP.

Exactly, it is solved by dynamic programming over subsets (Bellman; Held & Karp, 1962): let reach[S][v]\text{reach}[S][v] record whether some path that starts at vertex 0 visits exactly the set SS and ends at vv. Each entry is an OR over the possible last steps, for O(2nn2)O(2^n n^2) time and O(2nn)O(2^n n) bits, enough for nn up to about 20 (see Bitmask DP & the Held–Karp Algorithm). For undirected graphs, Björklund (2010) gave a randomized algorithm running in O∗(1.657n)O^*(1.657^n) time, the first to break the 2n2^n barrier.

One special case is easy. The line graph L(G)L(G) of a directed graph GG has a vertex for every edge of GG and an arc from ee to ff whenever ff starts where ee ends; its Hamiltonian cycles are exactly the Eulerian circuits of GG. The de Bruijn graph on nn-strings is the line graph of the one on (n−1)(n - 1)-strings, which is why a de Bruijn sequence, a Hamiltonian cycle through all nn-strings, takes only linear time.

DerivationProof
  1. u=x1, x2, …, xn=vu = x_1,\ x_2,\ \dots,\ x_n = v

    A maximal counterexample. Suppose GG satisfies the condition but has no Hamiltonian cycle. Adding edges preserves the condition, so add edges as long as no Hamiltonian cycle appears. The result is not complete, because KnK_n is Hamiltonian for n≥3n \ge 3; take non-adjacent uu and vv. Adding uvuv would create a Hamiltonian cycle, which must use uvuv, so the graph has a Hamiltonian path from uu to vv:

  2. u=x1→xi+1→xi+2→⋯→xn=v→xi→xi−1→⋯→x1u = x_1 \to x_{i+1} \to x_{i+2} \to \cdots \to x_n = v \to x_i \to x_{i-1} \to \cdots \to x_1

    Two index sets that cannot meet. Let A={i:uxi+1∈E}A = \{i : u x_{i+1} \in E\} and B={i:xiv∈E}B = \{i : x_i v \in E\}, both inside {1,…,n−1}\{1, \dots, n - 1\}, with ∣A∣=deg⁡(u)\abs{A} = \deg(u) and ∣B∣=deg⁡(v)\abs{B} = \deg(v). If some ii lay in both, this would be a Hamiltonian cycle:

  3. deg⁡(u)+deg⁡(v)=∣A∣+∣B∣≤n−1<n,a contradiction.\deg(u) + \deg(v) = \abs{A} + \abs{B} \le n - 1 < n,\quad\text{a contradiction.}

    Count. So AA and BB are disjoint subsets of a set of n−1n - 1 indices, and

Check your understanding

The complete bipartite graph K4,5K_{4,5} has 9 vertices, and every vertex has degree 4 or 5. Does it have a Hamiltonian cycle?

  1. Yes, by Dirac's theorem
  2. Yes: every complete bipartite graph has one
  3. No: a cycle alternates between the two sides, so it uses equally many vertices of each, but the sides have 4 and 5 vertices
  4. It cannot be decided without running Held–Karp
Show the answer

C. No: a cycle alternates between the two sides, so it uses equally many vertices of each, but the sides have 4 and 5 vertices

Every edge joins the two sides, so any cycle alternates and uses as many vertices on one side as on the other; with sides of 4 and 5, no cycle covers all 9. The minimum degree is 4, just below n/2=4.5n/2 = 4.5, so Dirac's theorem does not apply, and the example shows that its bound cannot be lowered: Km,m+1K_{m, m+1} has minimum degree (n−1)/2(n - 1)/2 and no Hamiltonian cycle.

Key takeaways

  • A connected graph has an Eulerian circuit iff every degree is even (directed: in-degree equals out-degree everywhere), and an open Eulerian trail iff exactly two vertices are odd (directed: one with an extra out-edge, one with an extra in-edge), which are its ends.
  • Hierholzer's algorithm walks until stuck, which parity allows only at the start, and splices closed detours into the circuit; with a stack and per-vertex pointers it runs in O(n+m)O(n + m).
  • Eulerian circuits of de Bruijn graphs give de Bruijn sequences and genome assemblies, the BEST theorem counts them in directed graphs, and the Chinese postman adds a minimum-weight matching of the odd vertices.
  • Hamiltonian cycle is NP-complete. Held–Karp decides it in O(2nn2)O(2^n n^2) time, Björklund's algorithm in O∗(1.657n)O^*(1.657^n) for undirected graphs, and Ore's condition, deg⁡u+deg⁡v≥n\deg u + \deg v \ge n for every non-adjacent pair, guarantees one.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

A connected undirected graph has six vertices of degrees 2, 3, 3, 4, 4 and 2. Which statement is true?

  1. It has an Eulerian circuit
  2. It has an Eulerian trail between the two vertices of degree 3, but no Eulerian circuit
  3. It has no Eulerian trail, because some degrees are odd
  4. It has an Eulerian trail that starts at a vertex of degree 4
Show the answer

B. It has an Eulerian trail between the two vertices of degree 3, but no Eulerian circuit

Exactly two vertices have odd degree, so an Eulerian trail exists, and it must start at one of them and end at the other. A circuit would need every degree to be even.

Question 2

In a directed graph whose edges form one weakly connected piece, one vertex has two more out-edges than in-edges, another has two more in-edges than out-edges, and every other vertex is balanced. Does it have an Eulerian trail?

  1. Yes, from the vertex with the surplus of out-edges to the one with the surplus of in-edges
  2. Yes, an Eulerian circuit, since the surpluses cancel
  3. No: the two ends of an open trail are each unbalanced by exactly 1
  4. Only if the graph is strongly connected
Show the answer

C. No: the two ends of an open trail are each unbalanced by exactly 1

A trail pairs every arrival at a vertex with a departure, except that the start gains one extra departure and the end one extra arrival. A surplus of 2 would need the trail to start at the same vertex twice: the edges split into at least two trails, never one.

Question 3

A de Bruijn sequence of order nn visits every string of length nn exactly once: a Hamiltonian cycle in the graph whose vertices are those strings. Why can it be found in linear time, although Hamiltonian cycle is NP-complete?

  1. That graph is the line graph of the de Bruijn graph on (n−1)(n - 1)-strings, so its Hamiltonian cycles are exactly the Eulerian circuits of the smaller graph
  2. NP-completeness does not apply to graphs with more than 2n2^n vertices
  3. Held–Karp runs in linear time on de Bruijn graphs
  4. Every regular graph has a Hamiltonian cycle, and DFS finds it
Show the answer

A. That graph is the line graph of the de Bruijn graph on (n−1)(n - 1)-strings, so its Hamiltonian cycles are exactly the Eulerian circuits of the smaller graph

Each nn-string is an edge of the de Bruijn graph on (n−1)(n - 1)-strings, from its prefix to its suffix, and two nn-strings can follow each other exactly when those edges are consecutive. Visiting every nn-string once is therefore walking every edge of the smaller graph once, an Eulerian circuit, which Hierholzer's algorithm finds. NP-completeness is a statement about all graphs; special families can be easy.

Question 4

A connected street network has exactly four intersections of odd degree. What does the cheapest closed walk that covers every street require?

  1. Nothing extra: an Eulerian circuit exists
  2. Walking two of its streets twice, whichever they are
  3. A Hamiltonian cycle through the four odd intersections
  4. Extra walking along shortest paths that pair up the four odd intersections at the least total length
Show the answer

D. Extra walking along shortest paths that pair up the four odd intersections at the least total length

The repeated walking must make every degree even, so it must join the odd intersections in pairs, and each pair is best joined along a shortest path. Of the three ways to pair four vertices, take the cheapest; in general this is a minimum-weight perfect matching on the odd vertices, which takes polynomial time (Edmonds & Johnson, 1973).

Further reading

  • L. Euler, "Solutio problematis ad geometriam situs pertinentis," Commentarii academiae scientiarum Petropolitanae 8 (1741), 128–140; dated 1736.
  • C. Hierholzer, "Ueber die Möglichkeit, einen Linienzug ohne Wiederholung und ohne Unterbrechung zu umfahren," Mathematische Annalen 6 (1873), 30–32.
  • P. A. Pevzner, H. Tang & M. S. Waterman, "An Eulerian path approach to DNA fragment assembly," Proceedings of the National Academy of Sciences 98(17) (2001), 9748–9753.
  • A. Björklund, "Determinant sums for undirected Hamiltonicity," SIAM Journal on Computing 43(1) (2014), 280–299; preliminary version at FOCS 2010.
  • J. A. Bondy & U. S. R. Murty, Graph Theory (Springer, 2008).