Try it first — give it 25 minutes
0/4 revealedStuck? Take one hint at a time. The struggle is where the pattern sticks.
The problem in plain English
There are n computers, numbered 0 to n − 1, and a list connections of cables. Each cable [a, b] directly links two computers. In one operation you can unplug any cable and plug it in between any two computers. Return the minimum number of operations needed so every computer can reach every other one, or -1 if it's impossible. n can be up to 10⁵, and so can the number of cables.
Example: n = 4, connections = [[0,1],[0,2],[1,2]] → 1. Computers 0, 1 and 2 form a triangle, and 3 is alone. The triangle has one cable it doesn't need, so move it to computer 3.
Start with brute force
You could try to simulate it: find a redundant cable, pick two disconnected groups, move the cable, and repeat. Choosing which cable and which groups sounds like a search problem. Trying combinations blows up fast, and even a careful simulation that rescans the graph after every move is O(n · (n + m)), about 10¹⁰ steps at the limits.
The good news is that you don't have to simulate anything once you see two counting facts.
Building the intuition
Fact 1: the budget. Any connected network on n computers needs at least n − 1 cables. A tree is the cheapest connected shape, and it has exactly n − 1 edges. So if len(connections) < n − 1, no amount of rearranging helps, and the answer is -1. That's one comparison.
Fact 2: the cost. Suppose the computers currently form k separate groups (connected components). Each cable you move can join at most two groups into one, so you need at least k − 1 moves.
Can you always do it in exactly k − 1? You need k − 1 spare cables, ones you can unplug without splitting a group. A group with s computers needs only s − 1 cables to stay connected, so the cables it needs, summed over all groups, is n − k. If you have at least n − 1 cables, the spares number at least (n − 1) − (n − k) = k − 1. Exactly enough.
So the whole problem collapses to: check the budget, then count components. Counting components while reading an edge list is a classic Union-Find job: start at n and subtract one on every union that actually merges two groups.
The optimal approach
- If
len(connections) < n − 1, return-1. - Build a DSU with
nnodes. Setcomponents = n. - For each cable
[a, b]: ifunion(a, b)returnstrue, docomponents -= 1. - Return
components − 1.
The subtle detail is doing the budget check first. Without it you'd return components − 1 even when there aren't enough cables to do the moves, like n = 6 with only 4 cables.
The code
Every solution below is tested against the examples and edge cases before it ships. Pick your language — we'll remember it.
class DSU:
def __init__(self, n: int):
self.parent = list(range(n)) # every node starts as its own root
self.size = [1] * n
def find(self, x: int) -> int:
root = x
while self.parent[root] != root:
root = self.parent[root]
# path compression: point every node we walked past straight at the root
while x != root:
nxt = self.parent[x]
self.parent[x] = root
x = nxt
return root
def union(self, a: int, b: int) -> bool:
ra, rb = self.find(a), self.find(b)
if ra == rb:
return False # already in the same group
if self.size[ra] < self.size[rb]:
ra, rb = rb, ra # union by size: hang the smaller tree under the bigger
self.parent[rb] = ra
self.size[ra] += self.size[rb]
return True
class Solution:
def makeConnected(self, n: int, connections: List[List[int]]) -> int:
# n computers need at least n - 1 cables to be connected at all
if len(connections) < n - 1:
return -1
dsu = DSU(n)
components = n
for a, b in connections:
if dsu.union(a, b):
components -= 1
# every cable we don't need is free to move, and we have enough of them,
# so joining k islands costs exactly k - 1 moves
return components - 1class DSU {
public:
vector<int> parent, sz;
DSU(int n) : parent(n), sz(n, 1) {
iota(parent.begin(), parent.end(), 0); // every node starts as its own root
}
int find(int x) {
int root = x;
while (parent[root] != root) root = parent[root];
// path compression: point every node we walked past straight at the root
while (x != root) {
int nxt = parent[x];
parent[x] = root;
x = nxt;
}
return root;
}
// "union" is a C++ keyword, so this one is called unite
bool unite(int a, int b) {
int ra = find(a), rb = find(b);
if (ra == rb) return false; // already in the same group
if (sz[ra] < sz[rb]) swap(ra, rb); // union by size: smaller tree under the bigger
parent[rb] = ra;
sz[ra] += sz[rb];
return true;
}
};
class Solution {
public:
int makeConnected(int n, vector<vector<int>>& connections) {
// n computers need at least n - 1 cables to be connected at all
if ((int)connections.size() < n - 1) return -1;
DSU dsu(n);
int components = n;
for (auto& c : connections) {
if (dsu.unite(c[0], c[1])) components--;
}
// we have enough spare cables, so joining k islands costs k - 1 moves
return components - 1;
}
};class DSU {
int[] parent, size;
DSU(int n) {
parent = new int[n];
size = new int[n];
for (int i = 0; i < n; i++) {
parent[i] = i; // every node starts as its own root
size[i] = 1;
}
}
int find(int x) {
int root = x;
while (parent[root] != root) root = parent[root];
// path compression: point every node we walked past straight at the root
while (x != root) {
int nxt = parent[x];
parent[x] = root;
x = nxt;
}
return root;
}
boolean union(int a, int b) {
int ra = find(a), rb = find(b);
if (ra == rb) return false; // already in the same group
if (size[ra] < size[rb]) { // union by size: smaller tree under the bigger
int t = ra; ra = rb; rb = t;
}
parent[rb] = ra;
size[ra] += size[rb];
return true;
}
}
class Solution {
public int makeConnected(int n, int[][] connections) {
// n computers need at least n - 1 cables to be connected at all
if (connections.length < n - 1) return -1;
DSU dsu = new DSU(n);
int components = n;
for (int[] c : connections) {
if (dsu.union(c[0], c[1])) components--;
}
// we have enough spare cables, so joining k islands costs k - 1 moves
return components - 1;
}
}class DSU {
constructor(n) {
this.parent = Array.from({ length: n }, (_, i) => i); // every node starts as its own root
this.size = new Array(n).fill(1);
}
find(x) {
let root = x;
while (this.parent[root] !== root) root = this.parent[root];
// path compression: point every node we walked past straight at the root
while (x !== root) {
const nxt = this.parent[x];
this.parent[x] = root;
x = nxt;
}
return root;
}
union(a, b) {
let ra = this.find(a), rb = this.find(b);
if (ra === rb) return false; // already in the same group
if (this.size[ra] < this.size[rb]) [ra, rb] = [rb, ra]; // union by size
this.parent[rb] = ra;
this.size[ra] += this.size[rb];
return true;
}
}
/**
* @param {number} n
* @param {number[][]} connections
* @return {number}
*/
var makeConnected = function (n, connections) {
// n computers need at least n - 1 cables to be connected at all
if (connections.length < n - 1) return -1;
const dsu = new DSU(n);
let components = n;
for (const [a, b] of connections) {
if (dsu.union(a, b)) components--;
}
// we have enough spare cables, so joining k islands costs k - 1 moves
return components - 1;
};Dry run
n = 6, connections = [[0,1],[0,2],[0,3],[1,2],[1,3]]. 5 cables ≥ n − 1 = 5, so the budget is fine.
| Cable | Merged? | components | Note |
|---|---|---|---|
| start | 6 | ||
| [0, 1] | yes | 5 | |
| [0, 2] | yes | 4 | |
| [0, 3] | yes | 3 | {0,1,2,3}, {4}, {5} |
| [1, 2] | no, same root | 3 | spare cable |
| [1, 3] | no, same root | 3 | spare cable |
Return 3 − 1 = 2: move the two spare cables to computers 4 and 5.
Complexity
- Time: O(n + m · α(n)), where
mis the number of cables. Building the DSU is O(n), and each union is effectively O(1). - Space: O(n) for the DSU. We never build an adjacency list.
Edge cases and traps
- Skipping the budget check. It's the only way the answer can be
-1, and it doesn't depend on the shape of the graph at all. - Counting spare cables and returning that. The answer is the number of groups minus one, not the number of spares. Extra spares just sit unused.
n = 1. Zero cables are enough.0 < 0is false, there's one component, so the answer is0.- Recursive DFS on 10⁵ nodes in Python. A long chain hits the recursion limit. Union-Find (or an iterative BFS) avoids the problem.
Say it in the interview
"Two facts. Connecting n computers needs at least n − 1 cables, so fewer than that is -1 right away. Otherwise, if there are k components I need k − 1 moves, and the spare cables are always enough, because the components only need n − k cables between them. So I count components with Union-Find: start at n and subtract one per successful union. O(n + m · α(n)) time, O(n) space."
Follow-ups interviewers ask
- "Prove the spares are enough." Components need
n − kcables in total to stay connected. Withm ≥ n − 1cables, the spares arem − (n − k) ≥ k − 1. - "Which cables would you move?" Every union that returns
falsehands you a spare cable. Pair the firstk − 1spares with one representative from each of the other groups. - "BFS instead?" Build an adjacency list and count flood fills. Same complexity, but it uses more memory for the list.
Practise the same idea
This is a bonus day of the free DSA plan 🐸
90 problems in the order that builds on itself, one a day, with a walkthrough like this for each. Tick them off and keep your streak.
Get the full roadmap — free