Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

Coding · Graphs

Moving cables to connect a network

Medium · Target 20 minutes · Graphs · Type asked atAmazonBloomberg

There are n computers, numbered 0 to n − 1, and a list of cables connections; each [a, b] joins computers a and b. You may unplug any cable and plug it in between any two computers. Return the smallest number of such moves that leaves every computer connected to every other, directly or through others, or −1 if it cannot be done.

Examples

InputOutputWhy
n = 4, connections = [[0, 1], [0, 2], [1, 2]]1Move the cable between 1 and 2 to join computer 3.
n = 6, connections = [[0, 1], [0, 2], [0, 3], [1, 2]]-1Five cables are needed to connect six computers; there are four.
n = 5, connections = [[0, 1], [0, 2], [3, 4], [2, 3]]0Already connected.

Constraints

  • 1 ≤ n ≤ 10⁵
  • 1 ≤ |connections| ≤ 10⁵
  • No cable joins a computer to itself

Hints

Hint 1

Connecting n computers needs at least n − 1 cables. With fewer, the answer is −1 whatever you do.

Hint 2

With enough cables, the answer is the number of separate groups minus one: each move can join two groups, and a group with a cycle always has a cable to spare.

Hint 3

Count the groups with union-find: start with every computer in its own set and merge the two ends of each cable. Each successful merge reduces the count by one.

Where people lose marks

  • Checking only that the graph is connected and forgetting the cable count: with fewer than n − 1 cables, −1 is the answer even if the groups could be joined in principle.
  • Counting groups as the number of distinct parent values without calling find: parents are not roots until the path is compressed.
  • Union without find: setting parent[a] = b links the nodes, not their groups, and can create cycles in the forest.
  • Recursion depth in find on long chains in languages with small stacks; use an iterative find or union by size.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.