Data Structures & AlgorithmsModerateTCS NQT Digital · Product Company SDE

Problem: Edges of an undirected graph on vertices 0–4 are processed in the given order: e1 = 0-1, e2 = 1-2, e3 = 2-3, e4 = 3-4, e5 = 4-0, e6 = 1-3. Using union-find, the first edge that joins two vertices already in the same component is the first cycle-closing edge. Which edge number (1-based) is it?

  1. A. 5
  2. B. 6
  3. C. 4
  4. D. 7

Correct answer: A. 5

Union-find reports a cycle as soon as an edge's endpoints already share a root. The first four edges form a path, and the fifth edge closes the ring 0-1-2-3-4.

More Coding Interview Problems questions

Exams that ask this topic