Data Structures & AlgorithmsVery hardProduct company OA

Problem: Count Hamiltonian paths (visit every junction exactly once) in a 5-vertex road graph with bitmask DP over (visited set, current vertex). What is printed (directed paths, undirected paths)?

Problem: Count Hamiltonian paths (visit every junction exactly once) in a 5-vertex road graph with bitmask DP over (visited set, current vertex). What is printed (directed paths, undirected paths)?
from functools import lru_cache
n = 5
E = [(0, 1), (0, 2), (1, 2), (1, 3), (2, 4), (3, 4)]
adj = [0] * n
for a, b in E: adj[a] |= 1 << b; adj[b] |= 1 << a
@lru_cache(None)
def ham(mask, u):
    if mask == (1 << n) - 1: return 1
    return sum(ham(mask | 1 << v, v) for v in range(n) if adj[u] >> v & 1 and not mask >> v & 1)
paths = sum(ham(1 << s, s) for s in range(n))
print(paths, paths // 2)
What is printed?
  1. A. 7 14
  2. B. 14 7
  3. C. 10 5
  4. D. 12 6

Correct answer: B. 14 7

ham(mask, u) counts completions from u having visited mask; summing over all start vertices counts each path once per direction, so the number of distinct (undirected) paths is half: 14 / 2 = 7. States: 2ⁿ·n, transitions n each → O(2ⁿ·n²), feasible for n ≤ 20 whereas n! permutations is not. Forgetting that a path and its reverse are the same route is the usual double count.

More Coding Interview Problems questions

Exams that ask this topic