Data Structures & AlgorithmsHardInfosys SP/DSE · Product Company SDE

Problem: n = 10⁵ cities connected by roads that are added one at a time; after each addition report the number of connected components. Which data structure fits?

  1. A. BFS from scratch after each addition – O(n) per road is fine
  2. B. Dijkstra after each addition
  3. C. A stack of roads
  4. D. Union-find (disjoint set union) with path compression and union by rank – near O(1) per road

Correct answer: D. Union-find (disjoint set union) with path compression and union by rank – near O(1) per road

Each union that joins two different sets reduces the component count by one; total O(m α(n)). Recomputing with BFS is O(n + m) per addition, about 10¹⁰ overall. Deletions would need offline tricks, but additions are what DSU handles best.

More Coding Interview Problems questions

Exams that ask this topic