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 , 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 time with Held–Karp, and prove Ore's sufficient condition.
Euler’s theorem
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.
A walk gets stuck only where it started. Let every degree be even and walk from along unused edges. On its -th arrival at a vertex , the walk has used an odd number of 's edges, so an unused one remains; the walk can only stop at , after closing a circuit :
Splice. If misses some edges, connectivity gives a vertex on with an unused edge. Removing 's edges subtracts an even number from every degree, so all remaining degrees are even; walk from to get a closed trail through , and insert it into at . Each splice uses new edges, so the process ends with every edge used:
Open trails. With exactly two odd vertices and , add an edge . Now every degree is even, so there is an Eulerian circuit; deleting the added edge from it leaves an Eulerian trail from to . (By the handshake lemma, the number of odd vertices is always even.)
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.
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 NoneEach edge is followed once, and each pointer nxt[u] only moves forward through 's list, so the time is . 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.
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.
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 that still has unused edges; the unused edges have even degrees, so the new walk from is a closed detour that returns to . Its vertices are popped, and output, before itself, so in the reversed output the detour sits exactly at : the splice of the proof.
Consecutive outputs are adjacent. The vertex output right after is the vertex that lay below on the stack, either at once or at the end of a detour that returns to , and the edge that pushed 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 over symbols is a cyclic sequence of length in which every string of length appears exactly once as a window. Build the de Bruijn graph: one vertex per string of length , and for each string an edge from to . Every vertex has edges in and 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.
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 appendsWith euler_walk from the previous step. For and 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 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 , its -mers, and make one vertex per -mer and one edge per -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 . 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 record whether some path that starts at vertex 0 visits exactly the set and ends at . Each entry is an OR over the possible last steps, for time and bits, enough for up to about 20 (see Bitmask DP & the Held–Karp Algorithm). For undirected graphs, Björklund (2010) gave a randomized algorithm running in time, the first to break the barrier.
One special case is easy. The line graph of a directed graph has a vertex for every edge of and an arc from to whenever starts where ends; its Hamiltonian cycles are exactly the Eulerian circuits of . The de Bruijn graph on -strings is the line graph of the one on -strings, which is why a de Bruijn sequence, a Hamiltonian cycle through all -strings, takes only linear time.
A maximal counterexample. Suppose 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 is Hamiltonian for ; take non-adjacent and . Adding would create a Hamiltonian cycle, which must use , so the graph has a Hamiltonian path from to :
Two index sets that cannot meet. Let and , both inside , with and . If some lay in both, this would be a Hamiltonian cycle:
Count. So and are disjoint subsets of a set of indices, and
The complete bipartite graph has 9 vertices, and every vertex has degree 4 or 5. Does it have a Hamiltonian cycle?
- Yes, by Dirac's theorem
- Yes: every complete bipartite graph has one
- No: a cycle alternates between the two sides, so it uses equally many vertices of each, but the sides have 4 and 5 vertices
- 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 , so Dirac's theorem does not apply, and the example shows that its bound cannot be lowered: has minimum degree 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 .
- 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 time, Björklund's algorithm in for undirected graphs, and Ore's condition, 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.
A connected undirected graph has six vertices of degrees 2, 3, 3, 4, 4 and 2. Which statement is true?
- It has an Eulerian circuit
- It has an Eulerian trail between the two vertices of degree 3, but no Eulerian circuit
- It has no Eulerian trail, because some degrees are odd
- 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.
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?
- Yes, from the vertex with the surplus of out-edges to the one with the surplus of in-edges
- Yes, an Eulerian circuit, since the surpluses cancel
- No: the two ends of an open trail are each unbalanced by exactly 1
- 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.
A de Bruijn sequence of order visits every string of length 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?
- That graph is the line graph of the de Bruijn graph on -strings, so its Hamiltonian cycles are exactly the Eulerian circuits of the smaller graph
- NP-completeness does not apply to graphs with more than vertices
- Held–Karp runs in linear time on de Bruijn graphs
- 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 -strings, so its Hamiltonian cycles are exactly the Eulerian circuits of the smaller graph
Each -string is an edge of the de Bruijn graph on -strings, from its prefix to its suffix, and two -strings can follow each other exactly when those edges are consecutive. Visiting every -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.
A connected street network has exactly four intersections of odd degree. What does the cheapest closed walk that covers every street require?
- Nothing extra: an Eulerian circuit exists
- Walking two of its streets twice, whichever they are
- A Hamiltonian cycle through the four odd intersections
- 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).