Skip to problem
←

Number of Operations to Make Network Connected

Medium 0 attempts

There are n computers numbered 0 through n - 1. Each pair [a, b] in connections represents an undirected cable between computers a and b. Computers can communicate through a path of one or more cables.

In one operation, remove an existing cable and reconnect it between two different computers of your choice. You cannot add new cables. Return the minimum number of operations needed to connect every computer into one network, or -1 if this is impossible. An already connected network, including a single computer, needs 0 operations.

For example, with n = 4 and connections = [[0,1],[0,2],[1,2]], computers 0, 1, and 2 form a cycle while computer 3 is isolated. Move cable [1,2] to [1,3]: all four computers remain connected, using one operation.

Function contract

Implement makeConnected(n, connections).

Output: Return the minimum number of cable moves, or -1 if connecting all computers is impossible.

Example 1

Input
n = 4
connections = [[0,1],[0,2],[1,2]]
Output
1

Example 2

Input
n = 1
connections = []
Output
0
Constraints
  • 1 <= n <= 10^5
  • 0 <= connections.length <= min(n*(n-1)/2,10^5)
  • Connections are distinct undirected edges between different computers.
  • Every endpoint is an integer in [0, n - 1].

Union-Find (Count Components)

A connected network of n computers needs at least n - 1 cables. If fewer cables exist, return -1 immediately.

Use union-find to count the connected components. A successful union reduces the component count by one; an edge within the same component is redundant. With c components, a spanning forest uses n - c cables, leaving E - (n - c) reusable cables. Since E >= n - 1, there are at least c - 1 reusable cables.

Each move can join at most two components, so at least c - 1 moves are necessary. Reusing one redundant cable for each join achieves that bound.

javascript
function makeConnected(n, connections) {
  if (connections.length < n - 1) return -1;
  const parent = Array.from({ length: n }, (_, i) => i);
  const size = Array(parent.length).fill(1);
  function find(x) {
    while (parent[x] !== x) {
      parent[x] = parent[parent[x]];
      x = parent[x];
    }
    return x;
  }
  function union(a, b) {
    a = find(a);
    b = find(b);
    if (a === b) return;
    if (size[a] < size[b]) [a, b] = [b, a];
    parent[b] = a;
    size[a] += size[b];
  }
  let components = n;
  for (const [a, b] of connections) {
    const pa = find(a),
      pb = find(b);
    if (pa !== pb) {
      union(pa, pb);
      components--;
    }
  }
  return components - 1;
}

Time: O(n + E α(n)), where E is the number of cables and α is the inverse Ackermann function | Space: O(n)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript