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?- A. 7 14
- B. 14 7
- C. 10 5
- 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
- Problem: a judge checks your rolling-hash solution with hash(s) = Σ s[i]·Bⁱ computed in unsigned 64-bit arithmetic (implicitly modulo…
- Problem: n ≤ 2·10⁵ values and q ≤ 2·10⁵ offline queries 'how many DISTINCT values are in a[l..r]?' (time limit 2 s). Which approach is…
- Problem: boxes (w, h) can nest when BOTH dimensions are strictly smaller. Find the longest nesting chain for n ≤ 2·10⁵. A candidate sorts…
- Problem: union–find runs m = 10⁶ operations on n = 10⁶ elements. Version X uses union by rank AND path compression; version Y uses path…
- Problem: a ring of n stalls holds 1 (occupied) or 0 (free). In one swap you exchange any two stalls. Find the minimum swaps to bring all…
- Problem: a stream of n = 2·10⁵ latencies; after each arrival report the median of the last k = 10⁵ values (sliding window median), time…