Data Structures & AlgorithmsModerateTCS NQT Digital · Product Company SDE

Problem: Build a minimum spanning tree with Prim's algorithm (lazy heap of edges) starting from node 0; report the total weight and the order nodes join.

Problem: Build a minimum spanning tree with Prim's algorithm (lazy heap of edges) starting from node 0; report the total weight and the order nodes join.
import heapq
def prim(n, edges):
    adj = [[] for _ in range(n)]
    for a, b, w in edges: adj[a].append((w, b)); adj[b].append((w, a))
    seen, h, total, order = set(), [(0, 0)], 0, []
    while h:
        w, u = heapq.heappop(h)
        if u in seen: continue
        seen.add(u); total += w; order.append(u)
        for e in adj[u]:
            if e[1] not in seen: heapq.heappush(h, e)
    return total, order
print(prim(5, [(0, 1, 4), (0, 2, 1), (1, 2, 2), (1, 3, 5), (2, 3, 8), (3, 4, 3), (2, 4, 9)]))
What is printed?
  1. A. (11, [0, 2, 1, 4, 3])
  2. B. (11, [0, 2, 1, 3, 4])
  3. C. (12, [0, 2, 1, 3, 4])
  4. D. (11, [0, 1, 2, 3, 4])

Correct answer: B. (11, [0, 2, 1, 3, 4])

Prim grows one tree, always adding the cheapest edge leaving it. From 0: edge 0-2 (1); then 2-1 (2) beats 0-1 (4); then 1-3 (5) beats 2-3 (8) and 2-4 (9); then 3-4 (3). Total 1 + 2 + 5 + 3 = 11. Stale heap entries for already-added nodes are skipped. O(E log E).

More Coding Interview Problems questions

Exams that ask this topic