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
INPUT GRAPHBACKTRACKINGRESULT PATH012Edges: 0-1, 1-2Adjacency List:[[1], [0,2], [1]]1Start at vertex 12Visit neighbors: 0, 23Try 0 → can reach 2?4Path found: 1→0→2[1, 0, 2]102All vertices visitedexactly onceKey Insight:Backtracking with visited tracking lets us explore all possible pathssystematically while avoiding cycles and dead ends through pruning.TutorialsPoint - Hamiltonian Path Finder | Backtracking Approach
Asked in
Google 25 Microsoft 18 Amazon 15 Meta 12
23.4K Views
Medium Frequency
~35 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen