Number of Operations to Make Network Connected
Explanation & Solution
Description
There are n computers numbered from 0 to n - 1 connected by ethernet cables connections forming a network where connections[i] = [ai, bi] represents a connection between computers ai and bi. Any computer can reach any other computer directly or indirectly through the network.
You can extract certain cables between two directly connected computers, and place them between any pair of disconnected computers to make them directly connected.
Return the minimum number of times you need to do this in order to make all the computers connected. If it is not possible, return -1.
Input: n = 4, connections = [[0,1],[0,2],[1,2]]
Output: 1
Explanation: Remove cable between 0 and 2, place between 2 and 3.
Constraints
1 <= n <= 10^51 <= connections.length <= min(n * (n - 1) / 2, 10^5)connections[i].length == 20 <= ai, bi < nai != bi- There are no repeated connections
Approach
Union Find pattern
1. Check Minimum Cable Requirement
- We need at least
n - 1cables to connectncomputers - If
connections.length < n - 1, return-1immediately
2. Initialize Union Find
- Create parent and rank arrays for
nnodes - Each computer starts as its own component
3. Union All Connected Computers
- For each connection
[a, b], union computersaandb - Redundant connections (where a and b are already connected) become spare cables
4. Count Connected Components
- Count nodes that are their own root (i.e.,
find(i) === i) - Each distinct root represents a separate connected component
5. Return Components - 1
- To connect
kcomponents, we needk - 1cable operations - Since we verified enough total cables exist, these operations are always possible
Key Insight
- If we have enough cables (≥ n-1), the answer is simply the number of components minus 1
- Redundant cables within components can always be repurposed to bridge separate components
Visualization
Press play to start bfs traversal