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?
- A. BFS from scratch after each addition – O(n) per road is fine
- B. Dijkstra after each addition
- C. A stack of roads
- 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
- Problem: Find the longest substring that appears at least twice in a string of length 10⁵. Which approach is efficient?
- Problem: A recursive solution for 'number of ways to partition n into parts' is memoised on (n, largest part allowed). With n ≤ 1000, how…
- Problem: A function has T(n) = T(n − 1) + T(n − 2) + O(1) without memoisation. What is its growth?
- Problem: Dijkstra is run with a binary heap but WITHOUT the 'skip stale entry' check (if d > dist[u]: continue). What happens?
- Problem: n ≤ 10⁵ points on a line; answer 'how many points lie in [l, r]?' for 10⁵ queries. What is the simplest efficient solution?
- Problem: Implement a queue using two stacks and report the dequeued values. python class Q: def init(self): self.inb, self.out = [], []…