Number of Operations to Make Network Connected
Pattern: Disjoint set union
With fewer than n - 1 cables, it is impossible. Otherwise every extra cable inside a group can be moved, and joining g separate groups needs g - 1 moves. Count the groups with union-find.
The problem
n computers are joined by cables [a, b]. In one move you may unplug a cable and plug it between two other computers.
Return the fewest moves to connect every computer, or -1 if it is impossible. Vertices are numbered from 0 and each edge is given as [u, v].
Think first
- How many cables does a connected network of n computers need?
- Where do the spare cables come from?
- How many moves join g groups?
Hints
Brute force, and why it fails
Simulate moving cables one by one: needless work.
The key insight
With enough cables, spares always exist, so the answer is only the number of groups minus one.
Dry run
n = 6, cables 0-1, 0-2, 0-3, 1-2, 1-3. 5 cables, at least n - 1 = 5.
Step 1 of 3
The plan
if cables < n - 1: -1
groups = components (union-find)
return groups - 1
Complexity
- Time
O(V + E α(V))- Space
O(V)
One union-find pass.
Edge cases
- Already connected: 0.
- Too few cables: -1.
- One computer: 0.
I've built my logic, show the code
Java
class Solution {
public int makeConnected(int n, int[][] connections) {
if (connections.length < n - 1) return -1; // n computers need at least n - 1 cables
int[] parent = new int[n];
for (int i = 0; i < n; i++) parent[i] = i;
int groups = n;
for (int[] c : connections) {
int a = find(parent, c[0]), b = find(parent, c[1]);
if (a != b) { parent[a] = b; groups--; }
}
return groups - 1; // spare cables join the groups one move at a time
}
private int find(int[] parent, int x) {
while (parent[x] != x) x = parent[x] = parent[parent[x]];
return x;
}
}C++
class Solution {
public:
int makeConnected(int n, vector<vector<int>>& connections) {
if (static_cast<int>(connections.size()) < n - 1) return -1; // n computers need at least n - 1 cables
vector<int> parent(n);
for (int i = 0; i < n; i++) parent[i] = i;
int groups = n;
for (const vector<int>& c : connections) {
int a = find(parent, c[0]), b = find(parent, c[1]);
if (a != b) { parent[a] = b; groups--; }
}
return groups - 1; // spare cables join the groups one move at a time
}
int find(vector<int>& parent, int x) {
while (parent[x] != x) x = parent[x] = parent[parent[x]];
return x;
}
};Python
class Solution:
def makeConnected(self, n: int, connections: list[list[int]]) -> int:
if len(connections) < n - 1:
return -1 # n computers need at least n - 1 cables
parent = list(range(n))
def find(x):
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return x
groups = n
for a, b in connections:
ra, rb = find(a), find(b)
if ra != rb:
parent[ra] = rb
groups -= 1
return groups - 1 # spare cables join the groups one move at a timeCommon mistakes
- Counting isolated computers wrong.
- Forgetting the cable count check.