Imagine you're a network administrator managing n computers numbered from 0 to n-1. These computers are connected by ethernet cables represented by the array connections, where connections[i] = [ai, bi] means computers ai and bi are directly connected.
Currently, any computer can reach any other computer either directly or through a series of connections. However, your network might be fragmented into separate groups that cannot communicate with each other.
Your mission: You can unplug cables between directly connected computers and reconnect them between any pair of disconnected computers. Find the minimum number of cable relocations needed to ensure all computers are connected in one unified network.
If it's impossible to connect all computers (not enough cables), return -1.
Input & Output
Visualization
Time & Space Complexity
E edges ร inverse Ackermann function (nearly constant)
Parent and rank arrays for Union-Find structure
Constraints
- 1 โค n โค 105
- 1 โค connections.length โค min(n*(n-1)/2, 105)
- connections[i].length == 2
- 0 โค ai, bi < n
- ai โ bi
- No repeated connections