Data Structures & AlgorithmsModerateProduct Company SDE · Amazon/Microsoft-style OA

Problem: Union-find with path compression answers which friends are in the same circle. How many circles remain after the unions?

Problem: Union-find with path compression answers which friends are in the same circle. How many circles remain after the unions?
parent = list(range(8))
def find(x):
    while parent[x] != x:
        parent[x] = parent[parent[x]]
        x = parent[x]
    return x
def union(a, b):
    ra, rb = find(a), find(b)
    if ra == rb: return False
    parent[ra] = rb; return True
res = [union(a, b) for a, b in [(0, 1), (2, 3), (1, 3), (4, 5), (0, 2), (6, 6)]]
print(len({find(i) for i in range(8)}), res)
What is printed?
  1. A. 5 [True, True, True, True, False, False]
  2. B. 4 [True, True, True, True, True, False]
  3. C. 4 [True, True, True, True, False, False]
  4. D. 3 [True, True, True, True, False, True]

Correct answer: C. 4 [True, True, True, True, False, False]

Unions merge {0,1,2,3} (0–2 is already connected through 1–3, so it returns False – that edge would close a cycle), {4,5}, and 6, 7 stay alone: 4 sets. A self-union (6,6) finds the same root and returns False. Near O(1) amortised per operation.

More Coding Interview Problems questions

Exams that ask this topic