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?- A. [1, 2, 2, 3]
- B. [1, 1, 2, 2]
- C. [2, 3, 3, 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
- Problem: Shortest route where exactly one road may be used at half price (one coupon). Dijkstra on states (junction, coupon used?). python…
- Problem: Each grid cell has an arrow; moving along a cell's arrow is free, moving in any other direction costs 1 (you change the arrow)…
- Problem: Courses with prerequisites; at most k = 2 courses per semester. Exact DP over bitmasks of finished courses versus 'take the k…
- Problem: Count 'heavy pairs' i < j with a[i] > 2·a[j] in O(n log n) using a Fenwick tree over coordinate-compressed values (both x and 2x…
- Problem: A segment tree stores (sum, best prefix, best suffix, best subarray) per node to answer 'maximum subarray sum inside a[l..r]'…
- Problem: Smallest period of a log pattern from its KMP prefix function: per = n − π[n − 1], and s is a whole repetition only if per…