Number of Operations to Make Network Connected (LeetCode 1319): Solution and Explanation

Medium
Depth First Search
Breadth First Search
Union Find
Graph

You have n computers and a list of cables. Moving one cable counts as one operation. Return the fewest moves that link every computer into one network, or -1 if there is not enough cable.

Intuition

Any network that links n computers needs at least n - 1 cables, because each cable can join at most two separate pieces. If the list is shorter than that, no rearrangement can work, so the answer is -1.

When there are enough cables but the network is split into groups, some group must contain a cable it does not need: a cable whose two ends were already linked through other cables. That spare cable can be unplugged without breaking its group.

Each moved spare cable joins two groups into one. Starting from k groups, it takes exactly k - 1 moves to end with one group. So the whole problem reduces to counting the connected groups.

Approach: Cable count check plus union-find

  1. If len(connections) < n - 1, return -1.
  2. Give every computer its own parent: parent[i] = i, and set components = n.
  3. For each cable [a, b], find the roots of a and b. If they differ, point one root at the other and decrease components. If they match, the cable is spare.
  4. Return components - 1.

Step-by-step example

n = 4, connections = [[0,1],[0,2],[1,2]]
  1. There are 3 cables and 4 computers need at least 3, so the check passes.
  2. Cable 0-1 joins two lone computers. Groups drop from 4 to 3.
  3. Cable 0-2 joins computer 2 to the group of 0 and 1. Groups drop to 2.
  4. Cable 1-2 connects two computers that already share a root, so it is spare.
  5. Two groups remain: {0, 1, 2} and {3}. Moving the spare cable to computer 3 joins them, so the answer is 2 - 1 = 1.

Code: Python, Java, C++

1class Solution:
2    def makeConnected(self, n: int, connections: List[List[int]]) -> int:
3        if len(connections) < n - 1:
4            return -1
5        parent = list(range(n))
6
7        def find(x):
8            while parent[x] != x:
9                parent[x] = parent[parent[x]]
10                x = parent[x]
11            return x
12
13        components = n
14        for a, b in connections:
15            ra, rb = find(a), find(b)
16            if ra != rb:
17                parent[ra] = rb
18                components -= 1
19        return components - 1
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n + m * α(n))

Setting up the parent array is O(n), and each of the m cables does two finds, which are nearly constant with path compression.

Space

O(n)

The parent array holds one entry per computer.

Other approaches

DFS or BFS over an adjacency list (time O(n + m), space O(n + m))

Build an adjacency list, then start a DFS from every unvisited computer and count how many searches you start. That count is the number of groups. It needs the extra adjacency list but no union-find.

Count spare cables explicitly (time O(n + m * α(n)), space O(n))

Run union-find and count both the groups and the spare cables, then return groups - 1 if spare >= groups - 1. It gives the same answer, since enough total cables always means enough spare ones.

Common mistakes

  • Skipping the n - 1 check and returning groups - 1 even when there is not enough cable.
  • Counting spare cables but forgetting that the answer is the number of groups minus one, not the number of spare cables.
  • Treating a computer with no cables as already connected. A lone computer is its own group and needs one move.
  • Writing a recursive find without path compression or rank, which can blow the stack on a long chain of 100,000 computers.

Frequently asked questions

Why is n - 1 cables always enough?

A tree on n computers uses exactly n - 1 cables. If you have at least that many and the network is split, the groups use fewer cables as trees than you have in total, so at least one group holds a spare cable you can move.

Do I need to know which cable to move?

No. The question only asks for the count. Any spare cable works, and each move joins two groups, so the count is groups - 1.

Is union-find required?

No. Any way of counting connected components works, including DFS or BFS. Union-find is convenient because it processes the cable list directly without building an adjacency list.