Using every edge once: Euler paths
🌍 In real life. Children love the puzzle of drawing a little house in one stroke, without lifting the pen or going over a line twice. A street sweeper wants to sweep every street exactly once. And a traveller holds a pile of plane tickets, Dhaka (DAC) to Chattogram (CGP), Dhaka to Sylhet (ZYL), Sylhet to Dhaka, and wants one trip from Dhaka that uses every ticket.
All three ask for an Euler path: a walk that uses every edge exactly once (vertices may repeat). Leonhard Euler solved it in 1736 for the bridges of Königsberg, which is where graph theory began. Interviews ask it as LeetCode 332, Reconstruct Itinerary.
The idea in one sentence: an Euler path exists when the degrees allow it (in an undirected graph, every vertex has an even degree, or exactly two have an odd one), and Hierholzer's algorithm finds it by walking along unused edges until it gets stuck, adding each stuck vertex to the route, and reading the route backwards at the end.
Its words:
- degree: how many edges touch a vertex
- Euler circuit: an Euler path that ends where it started
- Hierholzer's algorithm: a DFS that deletes each edge as it uses it and records vertices when they run out of edges
- dead end: a vertex with no unused edges left; it must be the last stop of its part of the trip
Why simply walking can fail. Always taking the alphabetically first ticket from DAC goes to CGP, and there you are stuck with the DAC → ZYL and ZYL → DAC tickets unused. Hierholzer's fix: a dead end isn't a failure, it is the end of the trip. Put CGP on the route (backwards), step back to DAC, and use the remaining tickets from there; that loop gets spliced in before CGP.
Watch the stack and the route:
When does an Euler path exist? Every time a walk passes through a vertex it uses two of its edges, one in and one out. So every vertex in the middle of the walk has an even degree; only the start and the end can be odd.
- Undirected: all degrees even → an Euler circuit, from anywhere; exactly two odd → an Euler path between those two; more odd vertices → impossible. (The edges must also be connected.)
- Directed: every vertex has as many edges out as in, except that the start may have one more out and the end one more in. The house you draw in one stroke works because its two bottom corners are the only odd ones: start at one and finish at the other.
Why Hierholzer's is correct. A vertex is put on the route only when all its edges are used, so it really is the end of what follows it. Each detour that starts from a vertex still on the stack is a closed loop (degrees are balanced), and it gets spliced in exactly where it belongs.
What it costs, by counting. Every edge is pushed once and popped once: O(E) for the walk, plus O(E log E) to sort the tickets when the alphabetical order matters.
def euler_kind(edges): # undirected edges
degree = {}
for a, b in edges:
degree[a] = degree.get(a, 0) + 1
degree[b] = degree.get(b, 0) + 1
odd = [v for v in sorted(degree) if degree[v] % 2]
if not odd:
return "circuit: start anywhere, end where you started"
if len(odd) == 2:
return f"path: from {odd[0]} to {odd[1]}"
return "impossible"
house = [("A", "B"), ("B", "C"), ("C", "D"), ("D", "A"), ("A", "C"), ("B", "D"), ("C", "E"), ("D", "E")]
print(euler_kind(house))
print(euler_kind([("A", "B"), ("B", "C"), ("C", "A")]))
print(euler_kind([("A", "B"), ("A", "C"), ("A", "D")]))
from collections import defaultdict
def itinerary(tickets, start):
out = defaultdict(list)
for a, b in sorted(tickets, reverse=True):
out[a].append(b) # pop() then gives the smallest first
route, stack = [], [start]
while stack:
v = stack[-1]
if out[v]:
stack.append(out[v].pop()) # use an unused ticket from v
else:
route.append(stack.pop()) # stuck: v's part of the trip is done
return route[::-1]
print(itinerary([("DAC", "CXB"), ("DAC", "CGP"), ("CGP", "DAC"), ("CXB", "DAC")], "DAC"))Mistakes and edge cases.
- Writing the vertex down when you arrive. Then the dead end CGP would sit in the middle of the trip; record a vertex when it is finished, and reverse at the end.
- Not removing used edges. Looking at
out[v][0]without popping it walks the same ticket for ever. - Sorting the wrong way.
pop()takes from the end, so the lists must be in reverse alphabetical order for the alphabetically first trip to come out. - Skipping the existence check. If the degrees don't allow a path, Hierholzer's still returns a list, but it misses some edges. Check that the route has E + 1 stops.
- Euler or Hamilton. An Euler path uses every edge once and is easy; a Hamiltonian path visits every vertex once, and no fast method is known.
Quiz
What does this print?
def euler_kind(edges): # undirected edges degree = {} for a, b in edges: degree[a] = degree.get(a, 0) + 1 degree[b] = degree.get(b, 0) + 1 odd = [v for v in sorted(degree) if degree[v] % 2] if not odd: return "circuit: start anywhere, end where you started" if len(odd) == 2: return f"path: from {odd[0]} to {odd[1]}" return "impossible" print(euler_kind([("A", "B"), ("B", "C"), ("C", "D")])) print(euler_kind([("A", "B"), ("B", "C"), ("C", "D"), ("D", "A")]))An undirected graph has four vertices with an odd degree. Does it have an Euler path?
- No: only the start and the end of a path can have an odd degree
- Yes, starting at any odd vertex
- Yes, if it is connected
In Hierholzer's algorithm, when is a vertex added to the route?
- When it has no unused edges left, so it can only be the end of what follows
- As soon as it is reached
- When it has the smallest name
itinerary([("DAC", "CXB"), ("DAC", "CGP"), ("CGP", "DAC"), ("CXB", "DAC")], "DAC") should give the alphabetically first trip, ['DAC', 'CGP', 'DAC', 'CXB', 'DAC'], but gives ['DAC', 'CXB', 'DAC', 'CGP', 'DAC']. Which line is wrong?
def itinerary(tickets, start): out = defaultdict(list) for a, b in sorted(tickets): out[a].append(b) route, stack = [], [start] while stack: v = stack[-1] if out[v]: stack.append(out[v].pop()) else: route.append(stack.pop()) return route[::-1]
Coding tasks
Write
euler_kind(edges)for an undirected, connected graph given as a list of(a, b)edges: return"circuit"if every degree is even,"path"if exactly two are odd, and"none"otherwise.Write
itinerary(tickets, start): use every ticket(from, to)exactly once, starting atstart; when there is a choice, take the alphabetically smaller airport. A full trip always exists.