Ctrl K

Rewire the Office Network

Medium
An office has n computers numbered 0 to n − 1. The list cables describes the cables already laid: a pair [a, b] is a cable between computers a and b. Two computers can talk if there is a path of cables between them, either direct or through other computers. In one move you may unplug any existing cable and run it between any two computers that are not yet directly connected. Return the fewest moves after which every computer can reach every other one. If that cannot be done, return -1.
Example 1
n=5, cables=[[0, 1], [1, 2], [2, 0], [3, 4]] → 1

Computers 0, 1 and 2 form a triangle, so one of its cables is spare. Moving it to join, say, 2 and 3 connects the whole network in one move.

Example 2
n=5, cables=[[0, 1], [1, 2], [3, 4]] → -1

Connecting 5 computers takes at least 4 cables, and there are only 3.

Example 3
n=3, cables=[[0, 2], [2, 1]] → 0
Constraints
  • 1 ≤ n ≤ 10⁵
  • 1 ≤ len(cables) ≤ min(n·(n − 1)/2, 10⁵)
  • 0 ≤ a, b < n, a ≠ b
  • No two computers share more than one cable
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsDo the Links Form a Tree MediumIsolated Groups in a Network MediumRatio Chain Queries MediumClusters of Linked Servers MediumThe Extra Cable Medium
loading Python…
Input
n=5, cables=[[0, 1], [1, 2], [2, 0], [3, 4]]
Expected
1

Run checks the first 3 tests in your browser. Submit checks all 88 tests on the server, hidden ones included.