Data Structures & AlgorithmsHardTCS NQT · Infosys pattern

Kruskal's algorithm: which edges are accepted, in order, for the graph below?

Kruskal's algorithm: which edges are accepted, in order, for the graph below?
edges = sorted([(7, 'A', 'B'), (5, 'A', 'D'), (8, 'B', 'C'), (9, 'B', 'D'), (7, 'B', 'E'),
                (5, 'C', 'E'), (15, 'D', 'E'), (6, 'D', 'F'), (8, 'E', 'F'), (9, 'E', 'G'), (11, 'F', 'G')])
p = {v: v for v in 'ABCDEFG'}
def f(x):
    while p[x] != x: x = p[x]
    return x
acc = []
for w, u, v in edges:
    if f(u) != f(v): p[f(u)] = f(v); acc.append(u + v)
print(acc, sum(w for w, u, v in edges if u + v in acc))
  1. A. ['AD', 'CE', 'DF', 'AB', 'BE', 'EF'] 38
  2. B. ['AD', 'CE', 'DF', 'AB', 'BC', 'EG'] 40
  3. C. ['AD', 'DF', 'CE', 'AB', 'BE', 'EG'] 39
  4. D. ['AD', 'CE', 'DF', 'AB', 'BE', 'EG'] 39

Correct answer: D. ['AD', 'CE', 'DF', 'AB', 'BE', 'EG'] 39

Sorted by weight (ties by name): AD 5, CE 5, DF 6, AB 7, BE 7 accepted; BC 8 and EF 8 would close cycles (C–E–B and E–B–A–D–F); BD 9 also a cycle; EG 9 accepted. 6 edges for 7 vertices, total 5 + 5 + 6 + 7 + 7 + 9 = 39. O(E log E).

More Trees, Graphs, Recursion and Dynamic Programming questions

Exams that ask this topic