Data Structures & AlgorithmsVery hardProduct Company SDE · Amazon/Microsoft-style OA

Problem: Return the length of the shortest path that visits every node of a small undirected graph (start and end anywhere, edges reusable).

Problem: Return the length of the shortest path that visits every node of a small undirected graph (start and end anywhere, edges reusable).
from collections import deque
def visit_all(g):
    n = len(g); full = (1 << n) - 1
    q = deque((i, 1 << i, 0) for i in range(n)); seen = {(i, 1 << i) for i in range(n)}
    while q:
        u, mask, d = q.popleft()
        if mask == full: return d
        for v in g[u]:
            st = (v, mask | 1 << v)
            if st not in seen: seen.add(st); q.append((v, st[1], d + 1))
print(visit_all([[1, 2, 3], [0], [0], [0]]), visit_all([[1], [0, 2, 4], [1, 3, 4], [2], [1, 2]]))
What is printed?
  1. A. 4 4
  2. B. 3 4
  3. C. 4 5
  4. D. 6 4

Correct answer: A. 4 4

BFS over states (node, visited mask) from all nodes at once. A star with centre 0 and three leaves needs 1 → 0 → 2 → 0 → 3 = 4 edges (revisiting the centre). The second graph: 0 → 1 → 4 → 2 → 3 = 4. O(2ⁿ · n²) states × edges – fine for n ≤ 12.

More Coding Interview Problems questions

Exams that ask this topic