Data Structures & AlgorithmsModerateCognizant · Capgemini pattern

What is printed? (detect a cycle in an undirected graph with union-find)

What is printed? (detect a cycle in an undirected graph with union-find)
def has_cycle(n, edges):
    p = list(range(n))
    def f(x):
        while p[x] != x: x = p[x]
        return x
    for u, v in edges:
        a, b = f(u), f(v)
        if a == b: return (u, v)
        p[a] = b
    return None
print(has_cycle(4, [(0, 1), (1, 2), (2, 3)]), has_cycle(4, [(0, 1), (2, 3), (1, 3), (0, 2)]))
  1. A. None (1, 3)
  2. B. None (0, 2)
  3. C. (2, 3) (0, 2)
  4. D. None None

Correct answer: B. None (0, 2)

An edge whose endpoints already share a root closes a cycle. The path 0–1–2–3 has none. In the second graph 0–1, 2–3 and 1–3 join everything; 0–2 then closes the cycle 0–1–3–2–0. Near O(E α(V)) with path compression.

More Trees, Graphs, Recursion and Dynamic Programming questions

Exams that ask this topic