28 · Union-Find & Minimum Spanning Trees
#1319 Number of Operations to Make Network Connected
frequently reported atAmazon
the problem
In plain words
n computers (0..n−1) are joined by ethernet cables connections[i] = [a, b]. In one operation you may unplug any cable and plug it between two computers. Return the minimum number of operations to connect all computers, or -1 if impossible.
in n = 4, connections = [[0,1],[0,2],[1,2]]
out 1
Move cable 1–2 to join computer 3.
in n = 6, connections = [[0,1],[0,2],[0,3],[1,2],[1,3]]
out 2
Two spare cables (1–2 and 1–3) bring in computers 4 and 5.
in n = 6, connections = [[0,1],[0,2],[0,3],[1,2]]
out -1
Only 4 cables; 6 computers need at least 5.
- 1 ≤ n ≤ 10⁵
- 1 ≤ connections.length ≤ min(n(n−1)/2, 10⁵)
- No repeated connections
your turn
Try it before you peek
Read the examples, say the brute force out loud, then write code: here or on LeetCode ↗. Stuck for 20 minutes? Open one hint at a time.
Solve it in the browser
LeetCode-style: complete the class. Compiled by the real javac (Java 17) and judged right here — nothing is sent anywhere.
Solutions are hidden so you can try first. Even 20 minutes of real effort makes the answer stick far better than reading it.
Marking the problem solved, or opening every hint, also shows it.
the aha
Key insight
patternUnion-Find (DSU)Graph DFS / BFS traversal
Fewer than n − 1 cables → impossible. Otherwise there are always enough spare cables, and joining c components needs exactly c − 1 moves.
solutions
From brute force to optimal
If cables ≥ n − 1, the answer is (number of components) − 1. Count them with an iterative DFS.
- Return -1 if connections.length < n − 1.
- Build adjacency lists.
- Count DFS starts; return count − 1.
Every node and cable is visited once (m = cables).
Adjacency lists, seen, and the stack.
class Solution { public int makeConnected(int n, int[][] connections) { if (connections.length < n - 1) return -1; // not enough cables, whatever we do List<List<Integer>> adj = new ArrayList<>(); for (int i = 0; i < n; i++) adj.add(new ArrayList<>()); for (int[] c : connections) { adj.get(c[0]).add(c[1]); adj.get(c[1]).add(c[0]); } boolean[] seen = new boolean[n]; int components = 0; for (int i = 0; i < n; i++) { if (seen[i]) continue; components++; ArrayDeque<Integer> stack = new ArrayDeque<>(); stack.push(i); seen[i] = true; while (!stack.isEmpty()) { int u = stack.pop(); for (int v : adj.get(u)) if (!seen[v]) { seen[v] = true; stack.push(v); } } } return components - 1; // one cable joins two components }}components = n; each cable that merges two different sets does components--.
- Return -1 if connections.length < n − 1.
- Union every cable, counting real merges.
- Return components − 1.
O(n) to initialise, near-constant per cable.
parent and size only — no adjacency lists needed.
class Solution { private int[] parent, size; private int find(int x) { if (parent[x] != x) parent[x] = find(parent[x]); return parent[x]; } public int makeConnected(int n, int[][] connections) { if (connections.length < n - 1) return -1; parent = new int[n]; size = new int[n]; for (int i = 0; i < n; i++) { parent[i] = i; size[i] = 1; } int components = n; for (int[] c : connections) { int ra = find(c[0]), rb = find(c[1]); if (ra == rb) continue; // a spare (redundant) cable if (size[ra] < size[rb]) { int t = ra; ra = rb; rb = t; } parent[rb] = ra; size[ra] += size[rb]; components--; } return components - 1; }}in the room
How to say it in the interview
talk track
- Prove the spare-cable claim: with m ≥ n − 1 cables and c components, a spanning forest uses n − c cables, leaving m − (n − c) ≥ c − 1 spares.
traps
- Returning the number of components — c components need only c − 1 moves.
- Returning the number of spare cables: spares only prove it's possible; the answer is still c − 1.
- Recursive DFS on a 10⁵-node chain can overflow the stack. Use DSU or an explicit stack.
what they ask next
Follow-ups
Which cables should you move?
Every cable whose union failed is a spare. Take one spare per extra component and use it to join that component to the first one.
What if you can't move cables, only buy new ones?
Then it's never impossible: you buy exactly c − 1 new cables, one per extra component.
before you submit
Edge cases to test
- Exactly n − 1 cables but some sit inside one cluster → still possible, the spares get moved.
- Already connected → 0 moves.
- One cable short of n − 1 → -1, without looking at the graph at all.
- n up to 10⁵: a recursive DFS can overflow the stack on a long chain — prefer DSU or an explicit stack.
practise next
Similar problems
- #547Number of ProvincesMediumin Union-Find & MST
- #323Number of Connected Components in an Undirected GraphMediumin Union-Find & MSTLeetCode Premium
- #684Redundant ConnectionMediumin Union-Find & MST