Number of Operations to Make Network Connected - Problem
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 are given an initial computer network connections. 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 & Output
Example 1 — Basic Network
$
Input:
n = 4, connections = [[0,1],[0,2],[1,2]]
›
Output:
1
💡 Note:
We have 4 computers. Computers 0,1,2 are connected in one group, computer 3 is isolated. We need 1 operation to connect computer 3 to any of the connected computers.
Example 2 — Not Enough Cables
$
Input:
n = 6, connections = [[0,1],[0,2]]
›
Output:
-1
💡 Note:
We have 6 computers but only 2 cables. To connect all 6 computers, we need at least 5 cables minimum. Since 2 < 5, it's impossible.
Example 3 — Already Connected
$
Input:
n = 6, connections = [[0,1],[0,2],[0,3],[1,2],[1,3]]
›
Output:
2
💡 Note:
We have 3 components: {0,1,2,3}, {4}, {5}. We need 2 operations to connect all components into one network.
Constraints
- 1 ≤ n ≤ 105
- 1 ≤ connections.length ≤ min(n*(n-1)/2, 105)
- connections[i].length == 2
- 0 ≤ connections[i][0], connections[i][1] < n
- connections[i][0] != connections[i][1]
- There are no repeated connections.
Visualization
Tap to expand
Understanding the Visualization
1
Input
n=4 computers, connections=[[0,1],[0,2],[1,2]]
2
Find Components
Identify separate network groups
3
Calculate Operations
Need components-1 operations
Key Takeaway
🎯 Key Insight: To merge k separate network components into one, you need exactly k-1 cable relocations
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code