IBM Online Assessment: Make Network Connected - Union Find
Question Description
You are given n nodes (0..n-1) and a list of bidirectional connections. The goal is to determine the minimum number of operations to make the entire network connected. An operation removes any existing connection and reassigns it to connect two nodes. If there are fewer than n-1 edges you should immediately return -1 since it's impossible to connect all nodes.
This problem tests graph connectivity and counting of redundant edges. A concise approach is:
- Validate feasibility: if m < n - 1 return -1.
- Build connectivity using Union-Find (or DFS/BFS) and count how many connected components you end up with.
- Compute how many edges are "redundant" (extra edges you can rewire). The total minimal edges needed inside components is (n - components). So redundant = m - (n - components). If redundant >= components - 1, you can connect all components with (components - 1) operations; otherwise return -1.
You should be ready to implement Union-Find with path compression and union by rank or an iterative DFS to avoid recursion depth issues. Time complexity: O(n + m). Space: O(n + m) (or O(n) with Union-Find). Be prepared to discuss edge cases (duplicate edges, self-loops, isolated nodes) and to output the actual list of rewire operations if asked.
Common Follow-up Questions
- •How would you produce the actual list of edge reassignments (which edges to remove and which pairs to connect) to achieve connectivity?
- •If connections were directed, how would you change the algorithm to make the directed graph strongly connected (or state why it's harder)?
- •Modify the problem so each rewire has a cost; design an algorithm to minimize total cost to connect all nodes (hint: relate to MST or minimum-cost augmentation).
- •Design a dynamic version: edges arrive or are removed online — how would you maintain component counts and compute minimal rewirings efficiently?
Related Questions
Explore More Questions
Practice This Question with AI
Get real-time hints, detailed requirements, and insightful analysis of the question.