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?- A. 4 4
- B. 3 4
- C. 4 5
- 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
- Problem: Count the number of ways to assign n distinct tasks to n workers where task i cannot go to worker i (derangements), modulo 10⁹ +…
- Problem: Reconstruct a queue of people (h, k) where k = number of people in front with height ≥ h. python def rebuild(people)…
- Problem: Find the minimum number of refuelling stops to travel a distance, given stations (position, fuel) and start fuel. python import…
- Problem: A printer raises ink levels by choosing any contiguous block of cartridges and adding 1 unit to each in one operation. Starting…
- Problem: Count contiguous subarrays whose max − min ≤ k, using two monotonic deques and a shrinking left edge. python from collections…
- Problem: Return the k-th smallest absolute difference among all pairs of readings (n up to 10⁵, so the n² pairs cannot be listed). Binary…