Data Structures & AlgorithmsHardProduct Company SDE pattern

Prim's algorithm from vertex 0 on the undirected graph below. In what order are vertices added and what is the MST weight?

Prim's algorithm from vertex 0 on the undirected graph below. In what order are vertices added and what is the MST weight?
import heapq
edges = [(0, 1, 4), (0, 7, 8), (1, 2, 8), (1, 7, 11), (2, 3, 7), (2, 8, 2), (2, 5, 4),
         (3, 4, 9), (3, 5, 14), (4, 5, 10), (5, 6, 2), (6, 7, 1), (6, 8, 6), (7, 8, 7)]
g = {i: [] for i in range(9)}
for u, v, w in edges: g[u].append((w, v)); g[v].append((w, u))
seen, pq, order, total = set(), [(0, 0)], [], 0
while pq:
    w, u = heapq.heappop(pq)
    if u in seen: continue
    seen.add(u); order.append(u); total += w
    for e in g[u]: heapq.heappush(pq, e)
print(order, total)
  1. A. [0, 1, 7, 6, 5, 2, 8, 3, 4] 37
  2. B. [0, 1, 2, 8, 5, 6, 7, 3, 4] 39
  3. C. [0, 1, 2, 8, 5, 6, 7, 3, 4] 37
  4. D. [0, 7, 6, 5, 2, 8, 1, 3, 4] 37

Correct answer: C. [0, 1, 2, 8, 5, 6, 7, 3, 4] 37

Prim grows one tree, always adding the cheapest edge leaving it. After 0 (start) and 1 (weight 4), the cheapest crossing edges are 0–7 and 1–2, both 8; the heap holds (8, 7) and (8, 2), so the tie goes to vertex 2. Then 2–8 (2), 2–5 (4), 5–6 (2), 6–7 (1), 2–3 (7), 3–4 (9). Total 4 + 8 + 2 + 4 + 2 + 1 + 7 + 9 = 37 – the weight is the same whichever tied edge is taken. O(E log V).

More Trees, Graphs, Recursion and Dynamic Programming questions

Exams that ask this topic