Data Structures & AlgorithmsVery hardGoldman Sachs OA · LeetCode medium-hard

Problem: Count Hamiltonian paths (ordered sequences visiting every vertex once) in a small undirected graph with bitmask DP.

Problem: Count Hamiltonian paths (ordered sequences visiting every vertex once) in a small undirected graph with bitmask DP.
n = 5
E = [(0,1),(1,2),(2,3),(3,4),(4,0),(0,2)]
adj = [[False]*n for _ in range(n)]
for u, v in E: adj[u][v] = adj[v][u] = True
dp = [[0]*n for _ in range(1 << n)]
for v in range(n): dp[1 << v][v] = 1
for m in range(1 << n):
    for v in range(n):
        if dp[m][v]:
            for w in range(n):
                if not m >> w & 1 and adj[v][w]: dp[m | 1 << w][w] += dp[m][v]
print(sum(dp[(1 << n) - 1]))
What is printed?
  1. A. 10
  2. B. 12
  3. C. 24
  4. D. 14

Correct answer: D. 14

dp[mask][v] counts paths covering exactly 'mask' and ending at v. A 5-cycle alone gives 5 × 2 = 10 directed Hamiltonian paths; the chord 0–2 adds a few more. The DP's 14 matches checking all 120 permutations.

More Coding Interview Problems questions

Exams that ask this topic