Vibe Engines
YouTube

Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path

Algorithms · Graphs

Every Edge, Once.

Watch the explainer

The Seven Bridges of Königsberg asked: can you walk a route that crosses every bridge exactly once? Euler’s answer founded graph theory. Such a route — an Eulerian path — exists only when the graph is connected and has 0 or 2 vertices of odd degree. When it does, Hierholzer’s algorithm finds it in O(E): follow unused edges until you get stuck in a loop, then splice in more loops from any vertex that still has unused edges. Trace it edge by edge and watch the trail assemble.

O(E) time · exists iff connected & 0 or 2 odd-degree vertices · every edge used once
Eulerian path

A trail that uses every edge of the graph exactly once (vertices may repeat).

degree

How many edges touch a vertex. Odd-degree vertices decide whether a path can exist.

the rule

0 odd-degree vertices → Eulerian circuit; exactly 2 → Eulerian path between them; otherwise none.

Hierholzer

Walk until stuck (a closed loop), then splice loops from vertices with edges left.

euler.js — walk, get stuck, splice loops
Ready
Every vertex here has even degree, so an Eulerian circuit exists. Hierholzer walks unused edges until stuck, then backtracks — splicing any leftover loops in. Step to trace it.
0
at vertex
0/6
edges used
0
odd-degree
trail:

How it works

The degree rule falls right out of the definition. Every time an Eulerian trail passes through a vertex, it uses one edge to arrive and one to leave — consuming edges two at a time, so an interior vertex needs an even degree. The only vertices allowed an odd degree are the two endpoints of the trail (where you start with a leave and end with an arrival). Hence: a connected graph has an Eulerian circuit when every vertex is even, an Eulerian path when exactly two are odd (the endpoints), and neither otherwise.

1

Check the degree rule

Count odd-degree vertices. Zero → an Eulerian circuit exists; exactly two → an Eulerian path between them; anything else → no Eulerian trail at all.

2

Walk until stuck

From the start, keep following any unused edge. Because degrees are even, you can only get stuck back where you started — having traced a closed loop, though maybe not all edges yet.

3

Splice in leftover loops

If some vertex on your loop still has unused edges, start a new walk from there, trace another loop, and splice it into the trail at that vertex. Repeat until no edges remain.

✓

The stack method

Hierholzer implements this with a stack: push along unused edges; when a vertex has none left, pop it into the circuit. The reversed pop-order is the Eulerian trail, built in O(E).

Time
O(E)
Exists iff
0 or 2 odd
Each edge
used once
Founded
graph theory

The code

# Hierholzer — Eulerian circuit/path in O(E) def hierholzer(adj, start): # adj[v] = list of (neighbor, edge_id) used, stack, circuit = set(), [start], [] while stack: v = stack[-1] edge = next(((u, i) for u, i in adj[v] if i not in used), None) if edge: u, i = edge used.add(i); stack.append(u) # walk an unused edge else: circuit.append(stack.pop()) # stuck: retreat, record return circuit[::-1] # reversed = the trail
▶  Watch it explained

Euler Path: Time and Space Complexity, From First Principles

Quick check

1. When does a connected graph have an Eulerian path (but not a circuit)?

2. Why must interior vertices of an Eulerian trail have even degree?

3. In Hierholzer’s stack method, when is a vertex added to the circuit?

FAQ

What is an Eulerian path?

A trail through a graph that uses every edge exactly once (vertices may repeat). If it starts and ends at the same vertex it is an Eulerian circuit. Named after Euler, whose 1736 Seven Bridges of Königsberg solution founded graph theory.

When does an Eulerian path exist?

For a connected graph: an Eulerian circuit exists iff every vertex has even degree; an Eulerian path (non-circuit) exists iff exactly two vertices have odd degree, which become its endpoints. Any other number of odd-degree vertices → none.

How does Hierholzer’s algorithm work?

It builds the trail in O(E). Walk unused edges until stuck in a closed loop; if a vertex on the trail still has unused edges, walk another loop from it and splice it in; repeat until no edges remain. The stack version pushes along edges and pops edge-exhausted vertices into the circuit.

How is an Eulerian path different from a Hamiltonian path?

An Eulerian path visits every edge once; a Hamiltonian path visits every vertex once. Their difficulty differs enormously: Eulerian existence is an easy degree check and construction is O(E), while Hamiltonian-path existence is NP-complete.

The picture: two loops sharing one vertex

1 2 3 4 5 6 0 deg 2 1 deg 2 2 deg 4 3 deg 2 4 deg 2 first walk: edges 1, 2, 6 then stuck at 0 spliced in at 2: edges 3, 4, 5
The page’s demo graph: two triangles meeting at vertex 2. Every degree is even (2, 2, 4, 2, 2), so a circuit exists. The numbers show the order of edges in the finished trail 0 1 2 3 4 2 0. The walk from 0 closes the left triangle first and gets stuck; the right triangle is found later, when the algorithm backs up to vertex 2.

Worked example, step by step

Use the six edges [[0,1],[1,2],[2,0],[2,3],[3,4],[4,2]], start at vertex 0, and always take the lowest unused edge in adjacency order. The stack holds the current walk; out collects vertices as they are finished. The reversed out is the trail.

StepActionStackout
1walk edge 0–10 1—
2walk edge 1–20 1 2—
3walk edge 2–00 1 2 0—
4vertex 0 has no unused edge: pop it0 1 20
5walk edge 2–30 1 2 30
6walk edge 3–40 1 2 3 40
7walk edge 4–20 1 2 3 4 20
8vertex 2 has no unused edge: pop it0 1 2 3 40 2
9–13vertices 4, 3, 2, 1, 0 each have no unused edge: pop them in turn00 2 4 3 2 1 0

Steps 1–3 trace the left triangle and step 4 pops vertex 0 because it has no unused edge: the walk got stuck exactly where it began, as the even degrees promise. But three edges are still unused. The algorithm does not restart. The stack still holds 0, 1, 2, so vertex 2 is on top again with edges 2–3 and 4–2 unused, and the walk continues from there around the right triangle in steps 5–7. Only then do the pops resume. Reading out backwards gives 0 1 2 3 4 2 0: seven vertices for six edges, each edge used once. Notice that vertex 2 appears twice in the answer. That is the splice: the second loop is inserted into the first at the vertex where it attaches.

Complexity and trade-offs

CaseTimeSpaceWhy
Hierholzer with a cursor per vertexO(V + E)O(V + E)Each adjacency entry is skipped or taken once. On K₂₁ (210 edges) it examined 420 entries, exactly 2E; on K₄₁ (820 edges), 1,640.
Hierholzer, rescanning adjacency listsO(E · max degree)O(V + E)Same walk, no cursor. K₂₁: 6,420 entries examined. K₄₁: 49,640, a 30-fold gap against the cursor version.
Fleury (never cross a bridge unless forced)O(E²)O(V + E)A connectivity search at nearly every step. K₂₁: 61,880 entries. K₄₁: 927,360, which is 565 times the cursor version.
Eulerian circuit existence testO(V + E)O(V)Count degrees, then check that all edges lie in one connected component.
Hamiltonian path (every vertex once), for contrastO(2ⁿ · n²) exactO(2ⁿ · n)For 21 vertices the DP bound is 924,844,032 steps, against 420 for the Eulerian walk on the same graph.

The cursor is not an optimisation to add later; it is what makes the algorithm linear. All three methods return the same number of edges (210 and 820 here), so the difference is entirely in how often they look at an edge they have already used or a bridge they must avoid. The contrast with Hamiltonian paths is the real point: asking for edges once is easy, asking for vertices once is not, even though the two statements look nearly identical.

Common mistakes

  • Checking parity but not connectivity

    Two separate triangles, [[0,1],[1,2],[2,0],[3,4],[4,5],[5,3]], have all degrees equal to 2, so the parity test passes. Hierholzer from 0 returns [0, 1, 2, 0]: 3 edges walked out of 6. Compare the length of the result with E + 1 and return failure if it is shorter.

  • Starting at the wrong vertex for a path

    For [[0,1],[1,2],[2,0],[2,3]] the odd vertices are 2 and 3. Starting at 0 returns [0, 1, 2, 3, 0], which contains a jump 3→0 that is not an edge. Starting at 2 returns [2, 1, 0, 2, 3], which is valid. With exactly two odd vertices, start at one of them.

  • Marking an undirected edge as used in one direction

    If you record “used” per directed pair instead of per edge index, the edge can be walked again from the other end. On the triangle [[0,1],[1,2],[2,0]] that bug yields [0, 1, 0, 2, 1, 2, 0]: 6 steps for 3 edges. Mark by edge id.

  • Forgetting to reverse for a directed graph

    The stack method emits vertices in finishing order. For the directed edges 0→1, 1→2, 2→3 that is [3, 2, 1, 0], which walks every edge backwards. For undirected graphs the reversed trail is also valid, so the omission goes unnoticed until a directed case.

  • Counting a self-loop once

    A loop adds 2 to its vertex’s degree. For [[0,0],[0,1],[1,1]] the correct degrees are 3 and 3, two odd vertices, and the trail [0, 0, 1, 1] exists. Counting each loop once gives 2 and 2, which wrongly claims a circuit.

Where this shows up

  • Königsberg

    The four land masses of the old town had bridge counts of 5, 3, 3 and 3. Four odd vertices, more than two, so no walk crosses every bridge once. That single count is the whole proof.

  • De Bruijn sequences

    To build a cyclic binary string containing every 3-bit pattern once, make a graph whose vertices are the 2-bit strings and whose edges are the 3-bit strings, then find an Eulerian circuit. Run on this graph from 00, the circuit spells 00010111, and its eight cyclic windows are exactly 000 through 111.

  • Genome assembly

    Short reads can be cut into overlapping pieces, with each piece an edge between its prefix and suffix. A path that uses every edge once reconstructs a sequence consistent with all reads. Real data adds errors and repeats, but the model is an Eulerian path.

  • Routing and plotting

    Street sweeping, snow ploughing and pen-plotter drawing all want every segment covered with no repeats. When too many odd vertices rule that out, the standard fix is to repeat the cheapest edges so that the odd vertices pair up, which is the route inspection problem.

SOLVE IT YOURSELF

Solve it: cross every bridge exactly once

Euler settled the Königsberg bridges by counting odd-degree corners — no searching required. Hierholzer’s algorithm then builds the walk in linear time. Python or TypeScript.

YOUR TASK

Implement euler_path(n, edges) for an undirected graph: return a list of vertices using every edge exactly once, or None (null) if no such walk exists.

HINTS — 6 IDEAS
  1. The existence test is pure counting: the number of odd-degree vertices must be 0 (a closed circuit) or 2 (an open path). Any other count and it is impossible.
  2. Start at an odd-degree vertex if there is one; otherwise start anywhere with an edge.
  3. Hierholzer: push the start on a stack. Repeatedly walk any unused edge from the top of the stack, marking it used.
  4. When the top vertex has no unused edges left, pop it onto the output. Reverse the output at the end.
  5. Track edges as used by index, and keep a per-vertex cursor into its adjacency list so you never rescan — that is what makes it O(E) rather than O(E²).
  6. The degree test is necessary but not sufficient: a graph can have the right parity and still be disconnected. Check the walk actually used every edge — len(path) == len(edges) + 1 — before returning it.
CPython · WebAssembly

Keep going

Finished this one? 0 / 99 Algorithms done
NextSix Degrees: Union-Find Closest algorithm to this one

Explore the topic

See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.

More Algorithms