Hamiltonian Path Finder - Problem
A Hamiltonian path is a path in a graph that visits every vertex exactly once. Given an undirected graph represented as an adjacency list, determine if a Hamiltonian path exists.
If a Hamiltonian path exists, return the path as an array of vertices. If no such path exists, return an empty array.
Note: The graph is represented as an adjacency list where graph[i] contains all vertices adjacent to vertex i. Vertices are numbered from 0 to n-1.
Input & Output
Example 1 — Simple Path
$
Input:
graph = [[1],[0,2],[1]]
›
Output:
[1,0,2]
💡 Note:
Graph has vertices 0,1,2 with edges 0-1 and 1-2. Path 1→0→2 visits all vertices exactly once.
Example 2 — Triangle Graph
$
Input:
graph = [[1,2],[0,2],[0,1]]
›
Output:
[0,1,2]
💡 Note:
Complete triangle where every vertex connects to every other. Multiple Hamiltonian paths exist, return any one.
Example 3 — No Path Exists
$
Input:
graph = [[1],[0],[]]
›
Output:
[]
💡 Note:
Vertex 2 is isolated (no connections), so no path can visit all vertices.
Constraints
- 1 ≤ graph.length ≤ 15
- 0 ≤ graph[i].length ≤ graph.length
- graph[i][j] is a valid vertex index
- graph[i] does not contain duplicate vertices
- The graph is undirected: if j is in graph[i], then i is in graph[j]
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code