Data Structures & AlgorithmsModerateTCS NQT · union-find

Problem: How many connected components does the graph on vertices 0..5 with edges (0,1), (2,3), (4,5), (1,2) have? Run the union-find code.

Problem: How many connected components does the graph on vertices 0..5 with edges (0,1), (2,3), (4,5), (1,2) have? Run the union-find code.
p = list(range(6))
def f(x):
    while p[x] != x:
        p[x] = p[p[x]]
        x = p[x]
    return x
for u, v in [(0, 1), (2, 3), (4, 5), (1, 2)]:
    p[f(u)] = f(v)
print(len({f(i) for i in range(6)}))
What is printed?
  1. A. 2
  2. B. 1
  3. C. 3
  4. D. 4

Correct answer: A. 2

The components are {0,1,2,3} and {4,5}, so there are 2. The edge (1,2) merges the two pairs {0,1} and {2,3}.

More Coding Interview Problems questions

Exams that ask this topic