sagelearnai

Number of Operations to Make Network Connected

Difficulty: Medium · Pattern: Union-Find · LeetCode #1319

n computers are linked by connections (cables). In one operation you can unplug any cable and use it to connect two computers that aren't directly connected. Return the minimum number of operations needed to connect all the computers, or -1 if it's impossible.

Examples

text
n = 4, connections = [[0,1],[0,2],[1,2]]              →  1
n = 6, connections = [[0,1],[0,2],[0,3],[1,2],[1,3]]  →  2
n = 6, connections = [[0,1],[0,2],[0,3],[1,2]]        →  -1

Hints

  1. Connecting n nodes needs at least n − 1 cables. With fewer, it's impossible.
  2. With enough cables, each extra component needs exactly one moved cable, and redundant cables (ones inside a cycle) are always available to move.

Approach

If len(connections) < n − 1, return −1. Otherwise count the components k with Union-Find, and the answer is k − 1.

Why are there always enough spare cables? A component with s nodes needs only s − 1 edges, so the surplus is E − (n − k). Since E ≥ n − 1, that's at least k − 1. O(E · α(n)).

Complexity

Time: O(E · α(n)). Space: O(n).

Python solution
def makeConnected(n, connections):
    if len(connections) < n - 1:
        return -1
    parent = list(range(n))
    def find(x):
        while parent[x] != x:
            parent[x] = parent[parent[x]]
            x = parent[x]
        return x
    comps = n
    for a, b in connections:
        ra, rb = find(a), find(b)
        if ra != rb:
            parent[ra] = rb
            comps -= 1
    return comps - 1
JavaScript solution
function makeConnected(n, connections) {
  if (connections.length < n - 1) return -1;
  const parent = [...Array(n).keys()];
  const find = (x) => { while (parent[x] !== x) { parent[x] = parent[parent[x]]; x = parent[x]; } return x; };
  let comps = n;
  for (const [a, b] of connections) { const ra = find(a), rb = find(b); if (ra !== rb) { parent[ra] = rb; comps--; } }
  return comps - 1;
}