Data Structures & AlgorithmsHardTCS CodeVita · Microsoft SDE OA

Eight vertices 0..7 receive the edges (0,1), (2,3), (4,5), (1,2), (5,6) in that order in a disjoint-set structure with union by size and path halving. What is the size of the largest connected component after all edges are added?

Eight vertices 0..7 receive the edges (0,1), (2,3), (4,5), (1,2), (5,6) in that order in a disjoint-set structure with union by size and path halving. What is the size of the largest connected component after all edges are added?
n=8; E=[(0,1),(2,3),(4,5),(1,2),(5,6)]
p=list(range(n)); sz=[1]*n
def f(x):
    while p[x]!=x: p[x]=p[p[x]]; x=p[x]
    return x
for a,b in E:
    ra,rb=f(a),f(b)
    if ra!=rb:
        if sz[ra]<sz[rb]: ra,rb=rb,ra
        p[rb]=ra; sz[ra]+=sz[rb]
print(max(sz[f(i)] for i in range(n)))
What is printed?
  1. A. 3
  2. B. 4
  3. C. 5
  4. D. 12

Correct answer: B. 4

Union by size tracks each root's component size, so the answer is the largest root size. Counting roots gives the number of components, counting edges is unrelated to component sizes, and an average over non-singleton components is a different quantity.

More Coding Interview Problems questions

Exams that ask this topic