Number of Operations to Make Network Connected Problem
Description
LeetCode Problem 1319.
There are n computers numbered from 0 to n - 1 connected by ethernet cables connections forming a network where connections[i] = [a_i, b_i] represents a connection between computers a_i and b_i. Any computer can reach any other computer directly or indirectly through the network.
You are given an initial computer network connections. You can extract certain cables between two directly connected computers, and place them between any pair of disconnected computers to make them directly connected.
Return the minimum number of times you need to do this in order to make all the computers connected. If it is not possible, return -1.
Example 1:

Input: n = 4, connections = [[0,1],[0,2],[1,2]]
Output: 1
Explanation: Remove cable between computer 1 and 2 and place between computers 1 and 3.
Example 2:

Input: n = 6, connections = [[0,1],[0,2],[0,3],[1,2],[1,3]]
Output: 2
Example 3:
Input: n = 6, connections = [[0,1],[0,2],[0,3],[1,2]]
Output: -1
Explanation: There are not enough cables.
Constraints:
1 <= n <= 10^51 <= connections.length <= min(n * (n - 1) / 2, 10^5)connections[i].length == 20 <= a_i, b_i < na_i != b_i- There are no repeated connections.
- No two computers are connected by more than one cable.
Solution
Approach: Union-Find
Moving a cable never changes the number of cables, and a network of n computers needs at least n - 1 cables to be connected. So if there are fewer than n - 1 connections, the answer is -1 right away.
Otherwise the answer only depends on how many separate groups (connected components) the network has. If there are k of them, we need at least k - 1 moves, since each move joins at most two groups. And k - 1 moves are always possible: a group of s computers needs only s - 1 of its cables to stay connected, so the network has m - (n - k) spare cables, where m is the number of connections. With m >= n - 1, that is at least k - 1, enough to link the groups in a chain.
To count the groups, we use union-find: start with every computer as its own group, and for each cable [a, b] merge the groups of a and b if they differ, counting down the number of groups. find uses path halving, which keeps the trees shallow without recursion.
Complexity: O(n + m·α(n)) time, which is practically linear, and O(n) extra space for the parent array.
class Solution:
def makeConnected(self, n: int, connections: List[List[int]]) -> int:
if len(connections) < n - 1:
return -1 # connecting n computers takes at least n - 1 cables
parent = list(range(n))
def find(x: int) -> int:
while parent[x] != x:
parent[x] = parent[parent[x]] # path halving
x = parent[x]
return x
components = n
for a, b in connections:
ra, rb = find(a), find(b)
if ra != rb:
parent[ra] = rb
components -= 1
# Enough cables means enough spare ones: each extra component needs one move.
return components - 1