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?- A. (11, [0, 2, 1, 4, 3])
- B. (11, [0, 2, 1, 3, 4])
- C. (12, [0, 2, 1, 3, 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
- Problem: From index i of an array you may jump to i + a[i] or i − a[i] (staying inside). Can you reach any index holding 0? (BFS.) python…
- Problem: Paint-bucket fill: recolour the 4-connected region of the start cell's colour and report how many cells changed. python def…
- Problem: Rearrange a string so no two adjacent letters are equal ("" if impossible). Greedy: always place the most frequent remaining…
- Problem: A 'closed island' is a group of 0-cells (land) connected 4-directionally that does NOT touch the grid border. Count them. python…
- Problem: On a board of 'X' and 'O', capture every 'O' region not connected to the border by turning it into 'X'. Mark border-connected…
- Problem: Run Bellman–Ford from node 0 on a directed graph with negative edges, then check for a negative cycle with one more relaxation…