Number of Operations to Make Network Connected (LeetCode 1319): Solution and Explanation
You have n computers and a list of cables. Moving one cable counts as one operation. Return the fewest moves that link every computer into one network, or -1 if there is not enough cable.
Intuition
Any network that links n computers needs at least n - 1 cables, because each cable can join at most two separate pieces. If the list is shorter than that, no rearrangement can work, so the answer is -1.
When there are enough cables but the network is split into groups, some group must contain a cable it does not need: a cable whose two ends were already linked through other cables. That spare cable can be unplugged without breaking its group.
Each moved spare cable joins two groups into one. Starting from k groups, it takes exactly k - 1 moves to end with one group. So the whole problem reduces to counting the connected groups.
Approach: Cable count check plus union-find
- If
len(connections) < n - 1, return -1. - Give every computer its own parent:
parent[i] = i, and setcomponents = n. - For each cable
[a, b], find the roots ofaandb. If they differ, point one root at the other and decreasecomponents. If they match, the cable is spare. - Return
components - 1.
Step-by-step example
n = 4, connections = [[0,1],[0,2],[1,2]]
- There are 3 cables and 4 computers need at least 3, so the check passes.
- Cable 0-1 joins two lone computers. Groups drop from 4 to 3.
- Cable 0-2 joins computer 2 to the group of 0 and 1. Groups drop to 2.
- Cable 1-2 connects two computers that already share a root, so it is spare.
- Two groups remain: {0, 1, 2} and {3}. Moving the spare cable to computer 3 joins them, so the answer is 2 - 1 = 1.
Code: Python, Java, C++
1class Solution:
2 def makeConnected(self, n: int, connections: List[List[int]]) -> int:
3 if len(connections) < n - 1:
4 return -1
5 parent = list(range(n))
6
7 def find(x):
8 while parent[x] != x:
9 parent[x] = parent[parent[x]]
10 x = parent[x]
11 return x
12
13 components = n
14 for a, b in connections:
15 ra, rb = find(a), find(b)
16 if ra != rb:
17 parent[ra] = rb
18 components -= 1
19 return components - 11class Solution {
2 public int makeConnected(int n, int[][] connections) {
3 if (connections.length < n - 1) return -1;
4 int[] parent = new int[n];
5 for (int i = 0; i < n; i++) parent[i] = i;
6 int components = n;
7 for (int[] c : connections) {
8 int ra = find(parent, c[0]), rb = find(parent, c[1]);
9 if (ra != rb) {
10 parent[ra] = rb;
11 components--;
12 }
13 }
14 return components - 1;
15 }
16
17 private int find(int[] parent, int x) {
18 while (parent[x] != x) {
19 parent[x] = parent[parent[x]];
20 x = parent[x];
21 }
22 return x;
23 }
24}1class Solution {
2public:
3 int makeConnected(int n, vector<vector<int>>& connections) {
4 if ((int)connections.size() < n - 1) return -1;
5 vector<int> parent(n);
6 iota(parent.begin(), parent.end(), 0);
7 int components = n;
8 for (auto& c : connections) {
9 int ra = find(parent, c[0]), rb = find(parent, c[1]);
10 if (ra != rb) {
11 parent[ra] = rb;
12 components--;
13 }
14 }
15 return components - 1;
16 }
17
18private:
19 int find(vector<int>& parent, int x) {
20 while (parent[x] != x) {
21 parent[x] = parent[parent[x]];
22 x = parent[x];
23 }
24 return x;
25 }
26};Time and space complexity
O(n + m * α(n))
Setting up the parent array is O(n), and each of the m cables does two finds, which are nearly constant with path compression.
O(n)
The parent array holds one entry per computer.
Other approaches
DFS or BFS over an adjacency list (time O(n + m), space O(n + m))
Build an adjacency list, then start a DFS from every unvisited computer and count how many searches you start. That count is the number of groups. It needs the extra adjacency list but no union-find.
Count spare cables explicitly (time O(n + m * α(n)), space O(n))
Run union-find and count both the groups and the spare cables, then return groups - 1 if spare >= groups - 1. It gives the same answer, since enough total cables always means enough spare ones.
Common mistakes
- Skipping the n - 1 check and returning groups - 1 even when there is not enough cable.
- Counting spare cables but forgetting that the answer is the number of groups minus one, not the number of spare cables.
- Treating a computer with no cables as already connected. A lone computer is its own group and needs one move.
- Writing a recursive find without path compression or rank, which can blow the stack on a long chain of 100,000 computers.
Frequently asked questions
Why is n - 1 cables always enough?
A tree on n computers uses exactly n - 1 cables. If you have at least that many and the network is split, the groups use fewer cables as trees than you have in total, so at least one group holds a spare cable you can move.
Do I need to know which cable to move?
No. The question only asks for the count. Any spare cable works, and each move joins two groups, so the count is groups - 1.
Is union-find required?
No. Any way of counting connected components works, including DFS or BFS. Union-find is convenient because it processes the cable list directly without building an adjacency list.