Data Structures & AlgorithmsVery hardProduct company OA

Union–find with union by rank and full path compression. What is printed?

Union–find with union by rank and full path compression. What is printed?
p = list(range(8)); rank = [0] * 8
def find(x):
    if p[x] != x: p[x] = find(p[x])
    return p[x]
def union(a, b):
    a, b = find(a), find(b)
    if a == b: return False
    if rank[a] < rank[b]: a, b = b, a
    p[b] = a
    if rank[a] == rank[b]: rank[a] += 1
    return True
ops = [(0, 1), (2, 3), (1, 3), (4, 5), (6, 7), (5, 7), (3, 7), (0, 2)]
res = [union(a, b) for a, b in ops]
print(p, res.count(False), max(rank))
find(6)
print(p)
  1. A. [0, 0, 0, 0, 0, 4, 4, 4] 1 3 [0, 0, 0, 0, 0, 4, 0, 4]
  2. B. [0, 0, 0, 0, 0, 4, 4, 4] 1 3 [0, 0, 0, 0, 0, 4, 4, 4]
  3. C. [0, 0, 0, 0, 0, 0, 0, 0] 1 3 [0, 0, 0, 0, 0, 0, 0, 0]
  4. D. [0, 0, 0, 2, 0, 4, 4, 4] 1 2 [0, 0, 0, 2, 0, 4, 0, 4]

Correct answer: A. [0, 0, 0, 0, 0, 4, 4, 4] 1 3 [0, 0, 0, 0, 0, 4, 0, 4]

Unions 0–1, 2–3, 4–5, 6–7 make four rank-1 trees; 1–3 joins roots 0 and 2 (rank 2), 5–7 joins 4 and 6 (rank 2). For 3–7, find(3) compresses 3 → 0 and find(7) compresses 7 and 6 straight to 4; equal ranks, so 4 goes under 0 and rank 0 becomes 3. 0–2 is already joined (the only False). Compression only touches nodes on a find path, so 5, 6, 7 still point at 4 until find(6) re-routes just 6 to 0. Expecting every node to point at the root is the common misconception.

More Trees, Graphs, Recursion and Dynamic Programming questions

Exams that ask this topic