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?- A. 10
- B. 12
- C. 24
- 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
- Problem: Reconstruct an actual longest strictly increasing subsequence with the O(n²) DP and parent pointers (the first maximal end index…
- Problem: Minimum number of single-character insertions plus deletions to turn a into b (no replacements). python def insdel(a, b): m, n =…
- Problem: Fibonacci modulo 10⁹ + 7 by 2 × 2 matrix exponentiation in O(log n). python MOD = 109 + 7 def mul(A, B): return [[(A[0][0]B[0][0]…
- Problem: Count balanced parenthesis strings with n pairs whose nesting depth never exceeds d (DP over position and current depth). python…
- Problem: Count integers in [1, N] whose digits sum to S, with a digit DP over (position, sum so far, tight). python from functools import…
- Problem: Assign 4 workers to 4 jobs (one each) to minimise total cost, with a DP over the bitmask of used jobs. python cost = [[9, 2, 7…