Number of Operations to Make Network Connected

medium

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.

Hints

You can't create new cables — connecting n computers needs at least n-1.
If there are fewer than n-1 cables, it's impossible: return -1.
Otherwise the answer is the number of connected components minus one.

Common doubts

Each connected component beyond the first needs exactly one link to join the rest, so joining c components takes c-1 moves.
With ≥ n-1 cables and c components, at least c-1 edges are redundant (form cycles), and those are exactly the cables you can reattach.
Both count components; union-find also naturally counts redundant edges if you want to reason about spares.

Interview follow-ups

Track redundant edges (union of already-connected endpoints) and pair them with the components needing a link.
Connectivity becomes strong vs weak; the counting differs (you'd consider strongly connected components).

Fun facts

  • LeetCode 1319 — a component-count problem dressed up as network rewiring.
  • The n-1 lower bound is just 'a tree on n nodes has n-1 edges'.

Asked at

AmazonMicrosoft
Frequently Sometimes Occasionally
Example 1
Input: n = 4, connections = [[0,1],[0,2],[1,2]]
Output: 1
Move the redundant cable in {0,1,2} to connect computer 3.
Example 2
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.
Constraints

- 1 <= n <= 10^5 - 0 <= connections.length <= 10^5 - no duplicate cables, no self-loops

Solve this problem →