Data Structures & AlgorithmsModerateAmazon · Microsoft OA

Problem: Build a minimum spanning tree with Kruskal's algorithm and report its total weight.

Problem: Build a minimum spanning tree with Kruskal's algorithm and report its total weight.
edges = [(4,'A','B'),(3,'A','C'),(1,'B','C'),(2,'B','D'),(4,'C','D'),(2,'D','E'),(5,'C','E')]
par = {c: c for c in 'ABCDE'}
def find(x):
    while par[x] != x: x = par[x]
    return x
total = 0
for w, u, v in sorted(edges):
    ru, rv = find(u), find(v)
    if ru != rv: par[ru] = rv; total += w
print(total)
What is printed?
  1. A. 9
  2. B. 16
  3. C. 8
  4. D. 5

Correct answer: C. 8

Sorted edges: B–C 1, B–D 2, D–E 2, A–C 3 (connects A); every later edge closes a cycle, so the MST weight is 1 + 2 + 2 + 3 = 8. Choosing A–B (4) instead of A–C gives 9, sorting in descending order builds the maximum spanning tree (16), and stopping after V − 2 edges leaves A out (5).

More Coding Interview Problems questions

Exams that ask this topic