Number of Operations to Make Network Connected solution explained

Number of Operations to Make Network Connected asks how many cables you must move so that every machine in a network can reach every other, where a move unplugs one existing cable and plugs it between any two machines. If there are fewer than n - 1 cables it is impossible, so return -1. Otherwise the answer is the number of connected components minus one, which union-find or a graph search counts in about O(n + E) time.

By Published 8 min read

The problem in plain words

There are n machines numbered 0 to n - 1 and a list of cables, each joining two machines in both directions. Two machines can talk if a chain of cables connects them. In one move you may unplug any cable and plug its ends into any two machines you choose. Return the fewest moves needed so that every pair of machines can talk, or -1 if no number of moves can achieve it.

Networks written for this page
n and cablesAnswerWhy
n = 5, [0,1], [1,2], [0,2], [3,4]1Two groups. The triangle 0, 1, 2 has a spare cable to move across to 3 or 4
n = 6, [0,1], [2,3], [4,5]-1Three cables cannot connect six machines, which needs at least five
n = 4, [0,1], [0,2], [0,3], [1,2], [2,3]0Everything is already connected. Extra cables do no harm
n = 7, [0,1], [1,2], [2,0], [0,3], [3,1], [4,5]2Groups {0,1,2,3}, {4,5} and {6}. The first group has two spare cables, one for each join
n = 1, no cables0A single machine is already connected to itself
Networks written for this page. Scroll sideways on a small screen.

What the interviewer is checking

The coding part is short. The reasoning is the real test. The interviewer wants two arguments from you: why fewer than n - 1 cables makes it impossible, and why components - 1 moves are always enough when you do have n - 1. Candidates who only say "count components" without explaining where the spare cables come from often get pushed on it. The choice of union-find versus a search is open, and either is fine if you can say what it costs.

Why the formula holds

A connected network on n machines needs at least n - 1 cables, because each cable can reduce the number of separate groups by at most one, and you start from n groups. So fewer than n - 1 cables means -1. Now suppose there are at least n - 1 cables but k groups. A group of s machines needs only s - 1 cables to stay connected. Adding up over all groups, the network needs only n - k cables to keep every group intact, so at least (n - 1) - (n - k) = k - 1 cables are spare: they sit on a loop and can be removed without splitting their group. Each spare cable, moved, joins two groups. Every move merges at most two groups, so k - 1 moves is also the minimum.

Brute force: move spare cables one by one

To check the formula, simulate it. Repeat: find the groups with a search. If there is one group, stop. Otherwise look for a cable whose removal does not increase the number of groups, which means it is a spare. If none exists, return -1. If one exists, unplug it and use it to join the first two groups. Each round re-runs searches for every cable, so this is far too slow for real inputs, but it follows the story exactly.

def min_moves_slow(n, cables):
    cables = [list(c) for c in cables]

    def groups(links):
        adj = [[] for _ in range(n)]
        for a, b in links:
            adj[a].append(b)
            adj[b].append(a)
        label = [-1] * n
        count = 0
        for s in range(n):
            if label[s] == -1:
                label[s] = count
                stack = [s]
                while stack:
                    for nb in adj[stack.pop()]:
                        if label[nb] == -1:
                            label[nb] = count
                            stack.append(nb)
                count += 1
        return count, label

    moves = 0
    while True:
        k, label = groups(cables)
        if k == 1:
            return moves
        spare = next((i for i in range(len(cables))
                      if groups(cables[:i] + cables[i + 1:])[0] == k), None)
        if spare is None:
            return -1
        a = label.index(0)               # a machine in the first group
        b = label.index(1)               # a machine in the second group
        cables[spare] = [a, b]
        moves += 1
Python: simulate the moves. Polynomial but slow, used as the checker.

Optimal: count the components

Once the argument is clear, the solution is three lines of logic around a component counter. Check the cable count first. Then count groups with union-find: start with n groups and subtract one each time a cable joins two machines that were in different groups. The answer is the group count minus one.

def min_moves(n, cables):
    if len(cables) < n - 1:
        return -1
    boss = list(range(n))
    rank = [0] * n

    def find(x):
        root = x
        while boss[root] != root:
            root = boss[root]
        while boss[x] != root:           # second pass: point the path at the root
            boss[x], x = root, boss[x]
        return root

    groups = n
    for a, b in cables:
        ra, rb = find(a), find(b)
        if ra == rb:
            continue                     # a spare cable inside one group
        if rank[ra] < rank[rb]:
            ra, rb = rb, ra
        boss[rb] = ra
        if rank[ra] == rank[rb]:
            rank[ra] += 1
        groups -= 1
    return groups - 1
Python: union-find with union by rank, counting successful merges

The find function compresses the path in two passes without recursion, so a long chain of machines cannot hit Python's recursion limit. The cable check must come first: with too few cables the component count is still meaningful, but no amount of moving can fix the network.

function minMoves(n, cables) {
  if (cables.length < n - 1) return -1;
  const adj = Array.from({ length: n }, () => []);
  for (const [a, b] of cables) {
    adj[a].push(b);
    adj[b].push(a);
  }
  const seen = new Uint8Array(n);
  let groups = 0;
  for (let start = 0; start < n; start++) {
    if (seen[start]) continue;
    groups++;
    seen[start] = 1;
    const stack = [start];
    while (stack.length > 0) {
      for (const next of adj[stack.pop()]) {
        if (!seen[next]) {
          seen[next] = 1;
          stack.push(next);
        }
      }
    }
  }
  return groups - 1;
}
JavaScript: the same answer with an adjacency list and an iterative DFS

The search version stores every cable twice in the adjacency list, so it uses O(n + E) memory, while union-find needs only O(n). Both visit every cable once. In an interview, pick the one you can write without bugs and mention the other.

Complexity

n machines, E cables
ApproachTimeExtra space
Simulate moves with repeated searchesRoughly O(n × E × (n + E))O(n + E)
Union-find, rank and path compressionO(n + E α(n))O(n)
Adjacency list plus DFS or BFSO(n + E)O(n + E)
n machines, E cables. Scroll sideways on a small screen.

Edge cases

  • n = 1: zero moves, and zero cables is already enough.
  • No cables and n of 2 or more: fewer than n - 1 cables, so -1.
  • Exactly n - 1 cables but split into groups: the formula still works, because those cables must contain loops.
  • The same pair of machines joined by two cables: the second one is spare, and union-find counts it as such.
  • Machines that appear in no cable: each one is its own group and needs one move.
  • More cables than needed: extra spares do not change the answer.

Common mistakes

  • Returning the number of spare cables instead of components - 1.
  • Forgetting the -1 case, or checking it after counting and returning a positive number anyway.
  • Counting components only among machines that appear in cables, which ignores isolated machines.
  • Using recursive DFS or recursive find on a long chain and running out of stack.
  • Writing union without checking whether the two roots already match, so the group count drops too far.

Follow-up questions

  • Say which cables to move and where. Collect the spare cables found during union-find, then pair each with one machine from the next group in turn.
  • Cables have different costs to move. The problem becomes a minimum spanning tree question: keep the cheapest structure and decide which edges to reuse.
  • Cables are added over time and you must report the answer after each one. Union-find handles this naturally: keep the group count and the spare count up to date as each cable arrives.

How to explain it out loud

Fictional example

Two arguments, then the counter
Candidate
First, n machines need at least n minus one cables to be connected, so with fewer I return minus one.
Candidate
If I have enough, I count the groups. Say there are k. Each group only needs size minus one cables, so at least k minus one cables are spare, sitting on loops.
Interviewer
Why can't you do it in fewer moves?
Candidate
Each move adds one cable between groups, which merges at most two. Going from k groups to one needs k minus one merges.
Candidate
So I just count groups with union-find. That's about linear, and O(n) memory.

Most Stones Removed with Same Row or Column also boils down to "n minus the number of components", with a less obvious graph. Similar String Groups counts components where the edges have to be discovered by comparing strings. On a grid, Number of Islands counts components of land cells with the same search used here.

Practicing it with Natively

Interviewers mostly grade the spare-cable argument, so rehearse saying it in two or three sentences. When you practice on a Mac or Windows PC, Natively can read the network from a screenshot, suggest the components-minus-one approach and the cable-count check, and transcribe your explanation so you can see whether both arguments made it in. The page on how AI helps in coding interviews covers the wider practice routine.

Questions people ask

How do you solve Number of Operations to Make Network Connected?

If there are fewer than n - 1 cables, return -1. Otherwise count connected components with union-find or DFS and return the count minus one.

Why is the answer components minus one?

With at least n - 1 cables, at least components - 1 cables are spare, sitting on loops, so each can be moved to join two groups. Each move merges at most two groups, so fewer moves cannot work.

What is the time complexity?

O(n + E α(n)) with union-find and O(n) space, or O(n + E) time and space with an adjacency list and DFS.

Do isolated machines need a move?

Yes. A machine with no cables is its own component, so it adds one to the count of moves.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP