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.
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:
| Aspect | Euler Path/Circuit | Hamiltonian Path/Cycle |
|---|---|---|
| Traverses | Every edge exactly once | Every vertex exactly once |
| Existence check | Polynomial time (check degrees) | NP-complete (no fast check known) |
| Construction | O(V + E) with Hierholzer's algorithm | O(n!) backtracking or O(2^n * n^2) bitmask DP |
| Named after | Leonhard Euler (1736) | William Rowan Hamilton (1857) |
| Interview frequency | Medium-high (LC 332, 2097) | Medium (LC 847, 980) |
| Real-world use | Circuit testing, DNA assembly, route planning | TSP, 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.
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.
For an undirected connected graph:
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).
For a directed connected graph (where the underlying undirected graph is connected):
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 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 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.
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.
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.
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).
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.
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>
Common Mistakes:
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.
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.
For graphs with up to about 20 vertices, we can do better using dynamic programming with bitmask state compression. The idea is:
1011, vertices 0, 1, and 3 have been visited.dp[mask][i] = true if there is a path that visits exactly the vertices in mask and ends at vertex i.dp[1 << i][i] = true for each vertex i (a path that visits only vertex i).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.
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>
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.
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).
Space Complexity: O(V + E) for the graph representation, stack, and result list.
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.
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.
| Algorithm | Time | Space | Practical Limit |
|---|---|---|---|
| Hierholzer's (Euler) | O(V + E) | O(V + E) | Millions of edges |
| Hierholzer's + sorting | O(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.
| Criterion | Euler Path/Circuit | Hamiltonian Path/Cycle |
|---|---|---|
| Goal | Traverse every edge once | Visit every vertex once |
| Existence check | O(V + E), check vertex degrees | NP-complete, no fast general check |
| Construction algorithm | Hierholzer's, O(V + E) | Backtracking O(n!) or Bitmask DP O(2^n * n^2) |
| Graph type | Works on directed and undirected | Works on directed and undirected |
| Existence conditions | Well-defined (degree-based) | No simple necessary-and-sufficient condition |
| Special graphs | Exists in all complete graphs with odd vertices | Exists in all complete graphs (Dirac's theorem for dense graphs) |
| Key LeetCode problems | 332, 2097, 753 | 847, 980 |
| Interview approach | Check existence, then Hierholzer's | Check constraints (n <= 20?), then bitmask DP or backtracking |
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)
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.
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.
| Problem | Difficulty | Key Concept |
|---|---|---|
| Reconstruct Itinerary (LC 332) | Hard | Euler path, Hierholzer's, lexicographic order |
| Valid Arrangement of Pairs (LC 2097) | Hard | Euler path on directed graph, find start vertex |
| Cracking the Safe (LC 753) | Hard | De Bruijn graph, Euler circuit |
| Shortest Path Visiting All Nodes (LC 847) | Hard | Bitmask 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.
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.
| Aspect | Euler Path | Hamiltonian Path |
|---|---|---|
| Time Complexity | O(V + E) Hierholzer's | O(n!) backtracking, O(2^n * n^2) bitmask DP |
| Space Complexity | O(V + E) | O(n) backtracking, O(2^n * n) bitmask DP |
| Prerequisites | Degree conditions met, graph connected | No simple precondition |
| Best For | Edge traversal, circuit/route reconstruction | Visiting all nodes, TSP-like problems |
| Avoid When | Problem is about vertices, not edges | n > 20 (too slow even with bitmask DP) |