Data Structures & AlgorithmsHardGATE CS · ICPC regional

Elements 0 to 5 start as singletons. For each call union(a, b), in order: let ra and rb be the roots of a and b. If ra = rb nothing happens. Otherwise the root of the smaller set is attached below the root of the larger set, and when the two sets have equal size the root ra (of the first argument) stays the root. The calls are union(0, 4), union(4, 4), union(3, 1), union(0, 0), union(4, 4), union(4, 4), union(3, 0), union(0, 2), union(0, 3). Which element is the root of the set containing 4 after all calls?

  1. A. 3
  2. B. 4
  3. C. 0
  4. D. 2

Correct answer: A. 3

Union by size keeps the root of the larger tree; the tie rule decides the root only when sizes are equal. Attaching the first argument's root under the second, or using the smaller index as root, gives a different root.

More Trees, Graphs, Recursion and Dynamic Programming questions

Exams that ask this topic