AlgoMaster Logo

Euler and Hamiltonian Paths

23 min readUpdated April 5, 2026
Listen to this chapter
Unlock Audio

Euler and Hamiltonian Paths

import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem';

In 1736, the citizens of Konigsberg had a simple question: could you walk through the city, crossing each of its seven bridges exactly once, and return to where you started? Leonhard Euler proved the answer was no, and in doing so, he invented graph theory. The problem he solved, visiting every edge exactly once, defines what we now call an Euler path. A closely related but far harder question is: can you visit every vertex exactly once? That is the Hamiltonian path problem.

These two problems look deceptively similar. Both involve traversing a graph under constraints. But they sit on opposite ends of the computational complexity spectrum. Euler paths can be found in O(V + E) time with an elegant algorithm. Hamiltonian paths are NP-complete, meaning no known polynomial-time algorithm exists. Understanding both, and especially understanding why they are so different, is valuable for interviews and for building intuition about graph problems.

Euler vs Hamiltonian: The Critical Distinction

Before diving into algorithms, let us make sure the definitions are razor sharp, because confusing these two is a common mistake.

An Euler path visits every edge exactly once. An Euler circuit (also called an Euler cycle) does the same but starts and ends at the same vertex.

A Hamiltonian path visits every vertex exactly once. A Hamiltonian cycle does the same but starts and ends at the same vertex.

The following diagram illustrates both concepts on the same graph. On the left, an Euler path traverses every edge. On the right, a Hamiltonian path visits every vertex.

In the Euler path example, you must walk along all five edges. In the Hamiltonian path example, you only need to touch all four vertices (A -> B -> C -> D), using just three edges.

Here is a comparison that highlights the key differences:

AspectEuler Path/CircuitHamiltonian Path/Cycle
TraversesEvery edge exactly onceEvery vertex exactly once
Existence checkPolynomial time (check degrees)NP-complete (no fast check known)
ConstructionO(V + E) with Hierholzer's algorithmO(n!) backtracking or O(2^n * n^2) bitmask DP
Named afterLeonhard Euler (1736)William Rowan Hamilton (1857)
Interview frequencyMedium-high (LC 332, 2097)Medium (LC 847, 980)
Real-world useCircuit testing, DNA assembly, route planningTSP, scheduling, genome sequencing

Interview Insight: If an interviewer asks about the difference between Euler and Hamiltonian paths, they are testing whether you understand the edge-vs-vertex distinction and, more importantly, the complexity gap. Euler is polynomial. Hamiltonian is NP-complete. This single fact shapes every algorithmic decision you make.

Why They Matter

Euler Path Applications

  • Circuit board testing: Testing every connection (edge) on a circuit board exactly once is literally an Euler path problem. It minimizes test time while ensuring complete coverage.
  • Snow plow and street sweeping routing: A city wants to sweep every street exactly once. Each street is an edge, and finding the most efficient route is an Euler path/circuit problem.
  • DNA fragment assembly: In bioinformatics, short DNA reads are edges in a de Bruijn graph. Assembling the genome means finding an Euler path through these edges.
  • Network analysis: Traversing every link in a network for monitoring or inspection.

Hamiltonian Path Applications

  • Traveling Salesman Problem (TSP): Visit every city exactly once and return home with minimum cost. This is the Hamiltonian cycle problem with weights.
  • Scheduling and logistics: Visit every location exactly once, classic route optimization.
  • Genome sequencing: In some formulations, the overlap graph approach models sequencing as a Hamiltonian path problem.
  • Knight's tour: Can a chess knight visit every square on the board exactly once? That is a Hamiltonian path on the knight's move graph.

Euler Path: Existence Conditions

One of the most powerful things about Euler paths is that you can determine whether one exists just by looking at vertex degrees. No search required.

Undirected Graphs

For an undirected connected graph:

  • An Euler circuit exists if and only if every vertex has even degree.
  • An Euler path (that is not a circuit) exists if and only if exactly two vertices have odd degree. These two vertices must be the start and end of the path.
  • If more than two vertices have odd degree, no Euler path exists.

The intuition is straightforward. Every time you enter a vertex through one edge, you must leave through a different edge. If a vertex has even degree, you can always pair up entries and exits. If it has odd degree, you will get "stuck" at that vertex, so it must be a starting or ending point. You can have at most two such stuck points (start and end).

Directed Graphs

For a directed connected graph (where the underlying undirected graph is connected):

  • An Euler circuit exists if and only if every vertex has equal in-degree and out-degree.
  • An Euler path (not a circuit) exists if and only if:
  • At most one vertex has out-degree - in-degree = 1 (the start vertex).
  • At most one vertex has in-degree - out-degree = 1 (the end vertex).
  • All other vertices have equal in-degree and out-degree.

Interview Insight: In an interview, always check existence conditions before attempting to construct an Euler path. It takes O(V + E) just to verify, and if the conditions are not met, you can immediately return that no path exists. This shows the interviewer you understand the theory, not just the code.

Hierholzer's Algorithm

Hierholzer's algorithm is the standard O(V + E) method for finding an Euler path or circuit. It is elegant, efficient, and the basis for solving problems like LeetCode 332 (Reconstruct Itinerary).

The Core Idea

The naive approach to finding an Euler path is to start at a vertex and greedily follow edges, removing each edge as you traverse it. The problem with this greedy approach is that you can get stuck. You might arrive at a vertex where all remaining edges lead to parts of the graph you have already isolated, trapping yourself in a dead end with unvisited edges elsewhere.

Hierholzer's insight is to embrace getting stuck. When you reach a dead end, that dead end becomes part of your result. You then backtrack to a vertex that still has unused edges and explore from there, inserting the new sub-circuit into your result. This backtracking is naturally handled by a stack.

Algorithm Steps

  1. Choose the starting vertex. For an Euler circuit, start anywhere. For an Euler path, start at a vertex with odd degree (undirected) or with out-degree - in-degree = 1 (directed).
  2. Follow edges using a stack. Push the current vertex onto the stack. Pick any unused edge from the current vertex, remove it, and move to the neighbor. Repeat.
  3. When stuck (no unused edges), backtrack. Pop the current vertex from the stack and add it to the result. The new top of the stack becomes the current vertex.
  4. Continue until the stack is empty.
  5. Reverse the result. The result is built in reverse order, so reverse it at the end.

The "reverse" step is the key insight that many people miss. Because we add vertices to the result when we get stuck (during backtracking), the result is built from the end of the path backward. This is essentially a post-order traversal of the edge structure.

Algorithm Flowchart

Example Walkthrough: Reconstruct Itinerary (LeetCode 332)

Let us apply Hierholzer's algorithm to a real interview problem. You are given a list of airline tickets represented as pairs [from, to]. Reconstruct the itinerary starting from "JFK". If there are multiple valid itineraries, return the one with the smallest lexicographic order.

Problem Setup

This gives us the following directed graph:

For lexicographic order, we sort each adjacency list alphabetically. So JFK's neighbors are [ATL, SFO] (ATL comes first).

Step-by-Step Trace

The itinerary is JFK -> ATL -> JFK -> SFO -> ATL -> SFO. Every ticket is used exactly once.

Interview Insight: The reason we build the result in reverse is subtle. When we get stuck at a vertex with no unused edges, we know that vertex is the last stop on some sub-path. By adding stuck vertices to the result and then reversing, we correctly interleave the sub-circuits. Many candidates try to build the result forward and get confused when sub-circuits need insertion. The reverse approach handles this naturally.

Implementation: Euler Path (Hierholzer's Algorithm)

The following implementations solve LeetCode 332 (Reconstruct Itinerary). The key ideas are: build a sorted adjacency list (for lexicographic order), use a stack-based iterative approach, and build the result in reverse.

<Tabs> <TabItem value="java" label="Java" default>

</TabItem> <TabItem value="python" label="Python">

</TabItem> <TabItem value="cpp" label="C++">

</TabItem> <TabItem value="csharp" label="C#">

</TabItem> <TabItem value="go" label="Go">

</TabItem> <TabItem value="javascript" label="JavaScript">

</TabItem> <TabItem value="typescript" label="TypeScript">

</TabItem> </Tabs>

Code Explanation

  1. Adjacency list with priority queue: We use a min-heap (or priority queue) so that at each vertex, we always pick the lexicographically smallest unused edge. This guarantees the smallest lexicographic itinerary.
  2. Stack-based traversal: Instead of recursion, we use an explicit stack. The top of the stack is always the current vertex.
  3. Building result in reverse: When a vertex has no more unused edges, it is popped from the stack and added to the front of the result (or appended and reversed at the end). This is the post-order nature of Hierholzer's algorithm.

Common Mistakes:

  • Using a regular list instead of a priority queue and forgetting to sort. The problem requires lexicographic order.
  • Trying to build the path forward instead of in reverse. This fails when sub-circuits need to be inserted into the middle of the path.
  • Not handling the case where a vertex has no outgoing edges in the graph map. Always check before polling.

Hamiltonian Path: The Core Idea

Now we shift to a fundamentally harder problem. While Euler paths are about traversing every edge, Hamiltonian paths are about visiting every vertex exactly once. This seemingly small difference puts the problem in an entirely different complexity class.

There is no polynomial-time algorithm known for finding Hamiltonian paths in general graphs. The problem is NP-complete, which means that unless P = NP (widely believed to be false), we cannot do better than exponential time. In interviews, this matters because it tells you which tools to reach for.

Approach 1: Backtracking

For small graphs, the most intuitive approach is backtracking. Try every possible path, and if you get stuck (visited all vertices or hit a dead end), backtrack and try a different route.

The time complexity is O(n!) in the worst case, because at each vertex you might have up to n-1 choices, then n-2, and so on. For graphs with up to about 12-15 vertices, this is fast enough.

Approach 2: Bitmask DP

For graphs with up to about 20 vertices, we can do better using dynamic programming with bitmask state compression. The idea is:

  • Use a bitmask of n bits to represent which vertices have been visited. For example, if n = 4 and the bitmask is 1011, vertices 0, 1, and 3 have been visited.
  • Define dp[mask][i] = true if there is a path that visits exactly the vertices in mask and ends at vertex i.
  • Base case: dp[1 << i][i] = true for each vertex i (a path that visits only vertex i).
  • Transition: dp[mask][i] = true if there exists a vertex j such that dp[mask ^ (1 << i)][j] is true and there is an edge from j to i.

The time complexity is O(2^n n^2), and the space complexity is O(2^n n). With n = 20, that is about 20 million states, which is manageable.

Interview Insight: When you see a graph problem where n is small (up to 15-20) and you need to visit all vertices, bitmask DP should immediately come to mind. The constraint on n is the giveaway. Problems like "Shortest Path Visiting All Nodes" (LC 847) and "Shortest Superstring" use this technique.

Implementation: Hamiltonian Path

The following implementations check whether a Hamiltonian path exists in an undirected graph using backtracking. This approach works well for small n (up to about 15).

<Tabs> <TabItem value="java" label="Java" default>

</TabItem> <TabItem value="python" label="Python">

</TabItem> <TabItem value="cpp" label="C++">

</TabItem> <TabItem value="csharp" label="C#">

</TabItem> <TabItem value="go" label="Go">

</TabItem> <TabItem value="javascript" label="JavaScript">

</TabItem> <TabItem value="typescript" label="TypeScript">

</TabItem> </Tabs>

Code Explanation

The backtracking approach is straightforward: try every possible starting vertex, then recursively try to extend the path by visiting unvisited neighbors. If we successfully visit all n vertices, a Hamiltonian path exists. If we exhaust all options from a vertex, we backtrack and try a different neighbor.

The critical observation is that we must try every starting vertex, because a Hamiltonian path might exist starting from vertex 3 but not from vertex 0. This is different from Euler paths, where the starting vertex is determined by the degree conditions.

For the bitmask DP approach (useful when n is up to 20), the key recurrence is: for each state (bitmask, last vertex), check if any predecessor state leads to it. LeetCode 847 (Shortest Path Visiting All Nodes) is the canonical problem for this technique, and it combines BFS with bitmask state representation.

Complexity Analysis

Euler Path (Hierholzer's Algorithm)

Time Complexity: O(E log E) for the LeetCode 332 variant (due to sorting adjacency lists for lexicographic order). Without the sorting requirement, pure Hierholzer's runs in O(V + E).

  • Building the adjacency list: O(E)
  • Sorting each adjacency list: O(E log E) total across all vertices
  • Traversal: O(V + E), since each edge is followed exactly once and each vertex is pushed/popped from the stack at most degree + 1 times

Space Complexity: O(V + E) for the graph representation, stack, and result list.

Hamiltonian Path (Backtracking)

Time Complexity: O(n! * n) in the worst case. At each of n levels, you might try up to n-1 neighbors, giving roughly n! paths to explore. The extra n factor comes from trying each starting vertex.

Space Complexity: O(n) for the recursion stack and visited array.

Hamiltonian Path (Bitmask DP)

Time Complexity: O(2^n * n^2). There are 2^n possible bitmask states, n possible ending vertices for each state, and for each (state, vertex) pair, we check up to n predecessors.

Space Complexity: O(2^n * n) for the DP table.

AlgorithmTimeSpacePractical Limit
Hierholzer's (Euler)O(V + E)O(V + E)Millions of edges
Hierholzer's + sortingO(E log E)O(V + E)Millions of edges
Backtracking (Hamiltonian)O(n!)O(n)n up to ~15
Bitmask DP (Hamiltonian)O(2^n * n^2)O(2^n * n)n up to ~20

Interview Insight: When discussing complexity in an interview, always mention the practical limits. Saying "Hierholzer's is O(V + E) so it handles millions of edges easily" or "bitmask DP works because the constraint says n <= 20, giving us about 20 million states" shows you understand not just the theory but how to apply it.

Euler vs Hamiltonian: Comparison Table

CriterionEuler Path/CircuitHamiltonian Path/Cycle
GoalTraverse every edge onceVisit every vertex once
Existence checkO(V + E), check vertex degreesNP-complete, no fast general check
Construction algorithmHierholzer's, O(V + E)Backtracking O(n!) or Bitmask DP O(2^n * n^2)
Graph typeWorks on directed and undirectedWorks on directed and undirected
Existence conditionsWell-defined (degree-based)No simple necessary-and-sufficient condition
Special graphsExists in all complete graphs with odd verticesExists in all complete graphs (Dirac's theorem for dense graphs)
Key LeetCode problems332, 2097, 753847, 980
Interview approachCheck existence, then Hierholzer'sCheck constraints (n <= 20?), then bitmask DP or backtracking

Common Patterns and Applications

Pattern 1: Edge Traversal and Reconstruction

Problem type: Given a set of edges (flights, pairs, dominoes), reconstruct a valid sequence that uses every edge exactly once.

How Euler paths help: These are direct applications of Hierholzer's algorithm. Build a directed graph from the edges, verify Euler path existence, then run Hierholzer's. The key twist is often lexicographic ordering, which requires sorting adjacency lists.

Examples: Reconstruct Itinerary (LC 332), Valid Arrangement of Pairs (LC 2097)

Pattern 2: De Bruijn Sequences

Problem type: Generate a sequence that contains every possible subsequence of length k exactly once.

How Euler paths help: A de Bruijn sequence of order k over an alphabet of size n is an Euler circuit in a de Bruijn graph. Each node represents a (k-1)-length string, and each edge represents a k-length string. Finding the Euler circuit gives you the de Bruijn sequence.

Example: Cracking the Safe (LC 753). You need to find the shortest string that contains every possible n-digit combination from digits 0 to k-1. This maps directly to an Euler circuit in a de Bruijn graph.

Pattern 3: Visit All Nodes (Bitmask BFS/DP)

Problem type: Find the shortest path that visits all nodes in a graph, possibly revisiting edges and vertices.

How Hamiltonian concepts help: While not a pure Hamiltonian path (since revisiting is allowed), the bitmask technique from Hamiltonian DP applies. Use BFS where each state is (current vertex, bitmask of visited vertices).

Example: Shortest Path Visiting All Nodes (LC 847). The state space is (node, visited bitmask), and BFS over this space finds the shortest path.

Interview Tips

  1. Always clarify edge vs vertex. When a problem says "visit everything once," ask: every edge or every vertex? This determines whether you are in Euler territory (polynomial) or Hamiltonian territory (exponential).
  2. Check the constraints. If n <= 20, bitmask DP is likely intended. If the problem involves edges and sequences, think Euler path.
  3. For Euler problems, verify existence first. Count degrees before constructing the path.
  4. For Hierholzer's, remember the reverse. The result is built backward. Use addFirst or reverse at the end.
  5. For lexicographic order, sort adjacency lists. Use priority queues or sorted lists to always pick the smallest neighbor first.

Practice Problems

ProblemDifficultyKey Concept
Reconstruct Itinerary (LC 332)HardEuler path, Hierholzer's, lexicographic order
Valid Arrangement of Pairs (LC 2097)HardEuler path on directed graph, find start vertex
Cracking the Safe (LC 753)HardDe Bruijn graph, Euler circuit
Shortest Path Visiting All Nodes (LC 847)HardBitmask BFS, visit all vertices

Recommended approach: Start with LC 332 to master Hierholzer's algorithm. Then try LC 2097, which is similar but requires you to identify the starting vertex yourself. LC 753 is a great exercise in recognizing a de Bruijn graph. Finally, LC 847 bridges into Hamiltonian-style bitmask techniques.

Interview Questions and Answers

Q1: How do you determine if an Euler path or circuit exists in a graph?

A: For an undirected graph, check vertex degrees. An Euler circuit exists if and only if every vertex has even degree and the graph is connected. An Euler path (non-circuit) exists if exactly two vertices have odd degree (these are the start and end vertices). For a directed graph, check in-degrees and out-degrees. An Euler circuit requires every vertex to have equal in-degree and out-degree. An Euler path requires at most one vertex with out-degree exceeding in-degree by 1 (the start) and at most one with in-degree exceeding out-degree by 1 (the end), with all others balanced. In both cases, the underlying graph must be connected. This check runs in O(V + E) time.

Q2: What makes Hamiltonian path NP-complete while Euler path is polynomial?

A: The fundamental difference is structural. For Euler paths, the existence condition depends only on vertex degrees, a global property that is easy to verify. You do not need to search for the path to know if one exists. And once you know it exists, Hierholzer's algorithm constructs it by following edges greedily with backtracking, each edge visited exactly once. For Hamiltonian paths, there is no simple structural condition that guarantees existence. You essentially need to explore exponentially many possible orderings of vertices. The problem reduces to checking all permutations, which is why it is NP-complete. In simple terms: Euler paths have polynomial structure (degrees determine everything), while Hamiltonian paths require exponential search (no shortcut around trying paths).

Q3: Why does Hierholzer's algorithm build the path in reverse?

A: Hierholzer's adds a vertex to the result when it gets stuck, meaning when there are no more unused edges from that vertex. The first vertex added to the result is the last stop on the path. As the algorithm backtracks, it discovers earlier stops. This is analogous to post-order traversal in trees: you process a node after processing all its descendants. Building in reverse naturally handles the insertion of sub-circuits. If you tried to build the path forward, you would face the problem of not knowing where to insert sub-circuits when the algorithm backtracks to a vertex with remaining unused edges. The reverse approach avoids this entirely.

Q4: How would you approach Cracking the Safe (LC 753)?

A: This problem asks for the shortest string containing every possible n-digit combination from k digits. The key insight is modeling it as a de Bruijn graph. Create a node for every (n-1)-digit string. Create a directed edge from node u to node v labeled with digit d if appending d to u gives an n-digit string whose last (n-1) digits are v. Finding an Euler circuit in this graph gives the de Bruijn sequence, which is the answer. Since every node has equal in-degree and out-degree (both equal to k), an Euler circuit is guaranteed to exist. Apply Hierholzer's algorithm starting from any node (such as "000...0"), and the circuit gives the shortest string. The result has length k^n + n - 1.

Summary

Key Takeaways

  • Euler paths traverse every edge exactly once. Hamiltonian paths visit every vertex exactly once. Despite sounding similar, they are in completely different complexity classes.
  • Euler path existence can be checked in O(V + E) by examining vertex degrees. No search is required.
  • Hierholzer's algorithm constructs Euler paths in O(V + E) time using a stack and building the result in reverse (post-order).
  • Hamiltonian paths are NP-complete. Use backtracking for n up to ~15, or bitmask DP (O(2^n * n^2)) for n up to ~20.
  • In interviews, always check whether the problem is asking about edges (Euler) or vertices (Hamiltonian) first. This determines your entire approach.
  • For Euler path problems with lexicographic ordering, use priority queues (min-heaps) in the adjacency list.

Quick Reference

AspectEuler PathHamiltonian Path
Time ComplexityO(V + E) Hierholzer'sO(n!) backtracking, O(2^n * n^2) bitmask DP
Space ComplexityO(V + E)O(n) backtracking, O(2^n * n) bitmask DP
PrerequisitesDegree conditions met, graph connectedNo simple precondition
Best ForEdge traversal, circuit/route reconstructionVisiting all nodes, TSP-like problems
Avoid WhenProblem is about vertices, not edgesn > 20 (too slow even with bitmask DP)

References