Data Structures & AlgorithmsModerateTCS NQT · union-find

Problem: Does the undirected graph with edges (0,1), (1,2), (2,0) contain a cycle? Run the union-find check and print 'cycle' or 'no cycle'.

Problem: Does the undirected graph with edges (0,1), (1,2), (2,0) contain a cycle? Run the union-find check and print 'cycle' or 'no cycle'.
p = list(range(3))
def f(x):
    while p[x] != x:
        x = p[x]
    return x
res = 'no cycle'
for u, v in [(0, 1), (1, 2), (2, 0)]:
    a, b = f(u), f(v)
    if a == b:
        res = 'cycle'
    else:
        p[a] = b
print(res)
What is printed?
  1. A. no cycle
  2. B. cycle
  3. C. 2
  4. D. undefined

Correct answer: B. cycle

The third edge joins two vertices already in one set, which is exactly the cycle test for undirected graphs with union-find.

More Coding Interview Problems questions

Exams that ask this topic