Data Structures & AlgorithmsModerateAccenture · Cognizant coding round pattern

Problem: Find the minimum total cost to connect all offices (minimum spanning tree) using Kruskal's algorithm.

Problem: Find the minimum total cost to connect all offices (minimum spanning tree) using Kruskal's algorithm.
def kruskal(n, edges):
    p = list(range(n))
    def f(x):
        while p[x] != x: p[x] = p[p[x]]; x = p[x]
        return x
    total = used = 0
    for w, u, v in sorted(edges):
        a, b = f(u), f(v)
        if a != b:
            p[a] = b; total += w; used += 1
    return total if used == n - 1 else -1
print(kruskal(5, [(4, 0, 1), (1, 0, 2), (3, 1, 2), (2, 1, 3), (5, 2, 3), (7, 3, 4), (6, 2, 4)]))
What is printed?
  1. A. 13
  2. B. 12
  3. C. 11
  4. D. 16

Correct answer: B. 12

Sorted edges: 1 (0–2), 2 (1–3), 3 (1–2), 4 (0–1, skipped: cycle), 5 (2–3, skipped), 6 (2–4), 7 (skipped). Total 1 + 2 + 3 + 6 = 12 with n − 1 = 4 edges. O(E log E).

More Coding Interview Problems questions

Exams that ask this topic