Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

Coding · Graphs

Routes that visit every node once

Hard · Target 30 minutes · Graphs

A directed graph has n nodes numbered 0 to n − 1; each pair [u, v] in edges is an edge from u to v. Return the number of Hamiltonian paths from source to destination: paths that start at source, end at destination, and visit every node of the graph exactly once.

Examples

InputOutputWhy
n = 4, edges = [[0,1],[0,2],[1,2],[2,1],[1,3],[2,3],[0,3]], source = 0, destination = 320 → 1 → 2 → 3 and 0 → 2 → 1 → 3. The edge 0 → 3 skips nodes.
n = 3, edges = [[0,2],[2,1]], source = 0, destination = 20The only route that visits all three nodes ends at 1.
n = 1, edges = [], source = 0, destination = 01A single node is a path of length zero.

Constraints

  • 1 ≤ n ≤ 12
  • No self-loops or repeated edges

Hints

Hint 1

Backtracking: extend a path from the source through unvisited nodes and count it when it has n nodes and ends at the destination.

Hint 2

Two partial paths that have visited the same set of nodes and stand at the same node have the same number of completions. Memoise on (set of visited nodes, current node).

Hint 3

Represent the visited set as a bitmask: dp[mask][v] = number of paths from the source covering exactly mask and ending at v.

Where people lose marks

  • Counting paths that reach the destination before all nodes are visited.
  • Letting a path pass through the destination and continue: the destination must be last.
  • Using plain backtracking for n = 12 on a dense graph: up to 10! partial orderings.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.