Data Structures & AlgorithmsHardTCS NQT · Accenture

Problem: Kruskal's algorithm with union-find is run on 5 nodes (0..4) with weighted edges (4,0,1), (1,1,2), (3,0,2), (2,2,3), (7,3,4), (5,1,4), given as (weight, u, v). What is the total MST weight?

Problem: Kruskal's algorithm with union-find is run on 5 nodes (0..4) with weighted edges (4,0,1), (1,1,2), (3,0,2), (2,2,3), (7,3,4), (5,1,4), given as (weight, u, v). What is the total MST weight?
def mst(n, edges):
    p = list(range(n))
    def f(x):
        while p[x] != x:
            p[x] = p[p[x]]
            x = p[x]
        return x
    t = 0
    for w, u, v in sorted(edges):
        a, b = f(u), f(v)
        if a != b:
            p[a] = b
            t += w
    return t
print(mst(5, [(4, 0, 1), (1, 1, 2), (3, 0, 2), (2, 2, 3), (7, 3, 4), (5, 1, 4)]))
What is printed?
  1. A. 10
  2. B. 19
  3. C. 6
  4. D. 11

Correct answer: D. 11

Kruskal takes weights 1, 2, 3 and 5 in sorted order, skipping 4 (0–1 closes a cycle) and 7, for a total of 11. Taking the four lightest edges without a cycle check gives 10, sorting in descending order builds the maximum spanning tree (19), and stopping after three edges leaves node 4 out (6).

More Coding Interview Problems questions

Exams that ask this topic