Data Structures & AlgorithmsHardAmazon · Microsoft OA

Problem: Total weight of a MAXIMUM spanning tree (Kruskal with edges sorted in decreasing order).

Problem: Total weight of a MAXIMUM spanning tree (Kruskal with edges sorted in decreasing order).
edges = [(7,0,1),(5,0,3),(8,1,2),(9,1,3),(7,1,4),(5,2,4),(15,3,4),(6,3,5),(8,4,5),(11,4,6),(9,5,6)]
par = list(range(7))
def f(x):
    while par[x] != x: x = par[x]
    return x
tot = 0
for w, u, v in sorted(edges, reverse=True):
    if f(u) != f(v): par[f(u)] = f(v); tot += w
print(tot)
What is printed?
  1. A. 39
  2. B. 59
  3. C. 52
  4. D. 60

Correct answer: B. 59

Take the heaviest edges that do not form a cycle: 15 (3–4), 11 (4–6), 9 (1–3), 9 (5–6), 8 (1–2), 7 (0–1) — six edges joining all 7 nodes, total 59. A minimum spanning tree on the same graph weighs 39.

More Coding Interview Problems questions

Exams that ask this topic