Data Structures & AlgorithmsVery hardProduct company OA

Problem: Roads are closed one by one; after each closure report the number of connected components. Process offline: start from the graph with all closures applied and add the roads back in reverse with union–find.

Problem: Roads are closed one by one; after each closure report the number of connected components. Process offline: start from the graph with all closures applied and add the roads back in reverse with union–find.
n = 6
edges = [(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (0, 5), (1, 4)]
removals = [(1, 2), (4, 5), (1, 4), (0, 5)]
p = list(range(n))
def find(x):
    while p[x] != x: p[x] = p[p[x]]; x = p[x]
    return x
comps = n
def union(a, b):
    global comps
    a, b = find(a), find(b)
    if a != b: p[a] = b; comps -= 1
for e in edges:
    if e not in removals: union(*e)
ans = [comps]
for e in reversed(removals):
    union(*e); ans.append(comps)
print(ans[::-1][1:])
What is printed?
  1. A. [1, 2, 2, 3]
  2. B. [1, 1, 2, 2]
  3. C. [2, 3, 3, 4]
  4. D. [1, 1, 2, 3]

Correct answer: D. [1, 1, 2, 3]

Union–find cannot delete edges, but read backwards a sequence of deletions is a sequence of insertions. With all four roads removed the graph has components {0, 1}, {5}, {2, 3, 4} → 3. Adding back (0, 5) → 2, (1, 4) → 1, (4, 5) → 1, and the answer list reversed gives the counts after each closure: [1, 1, 2, 3]. The first closure (1, 2) does not disconnect the 6-cycle-plus-chord graph. O((n + m) α(n)).

More Coding Interview Problems questions

Exams that ask this topic