There are n computers (0 .. n-1) and connections[i] = [a, b] is a cable directly connecting a and b. You may remove any cable and reattach it between any two computers. Return the minimum number of such moves to make all computers connected, or -1 if it's impossible.
Input: n = 4, connections = [[0,1],[0,2],[1,2]]
Output: 1
Move the redundant cable in {0,1,2} to connect computer 3.Input: n = 6, connections = [[0,1],[0,2],[0,3],[1,2],[1,3]] Output: 2 Two extra components (4 and 5) each need one link.
- 1 <= n <= 10^5 - 0 <= connections.length <= 10^5 - no duplicate cables, no self-loops
Two facts decide this instantly:
n computers needs at least n-1 cables. If you have fewer than n-1 cables total, it's impossible — return -1.components - 1: the network currently forms some number of connected components, and you need one link to join each extra component to the rest. There are always enough spare cables (redundant edges, whose endpoints were already connected) to do it — that's guaranteed the moment you have ≥ n-1 cables.So the whole problem is counting connected components — via union-find (count merges) or a DFS/BFS flood. O(n + E).
“When is it impossible?”
When there are fewer than n-1 cables.
“Where do the new links come from?”
Redundant (cycle) cables, which always suffice if you have ≥ n-1.
If there are fewer than n-1 cables it's impossible; otherwise I just need components-1 moves.
So I count connected components with union-find or a flood fill.
Worked example — n = 4, connections [[0,1],[0,2],[1,2]]
3 cables ≥ n-1 = 3; components = {0,1,2}, {3} -> 2
answer = 2 - 1 = 1
Fewer ⇒ impossible (-1).
One link per extra component.
Redundant edges cover the needed links once you have ≥ n-1.
| DFS component count | Union-Find | |
|---|---|---|
| Count via | flood each unvisited computer | merges (n minus successful unions) |
| Time | O(n+E) | O(n + E·α) |
| Answer | components - 1 | components - 1 |
Both count the same components. Full code is in the Approaches selector below.
Key takeaway
If cables < n-1, return -1. Otherwise the answer is (number of connected components) - 1. Count components with union-find or DFS. O(n + E).
if edges < n-1: return -1 return componentCount - 1