777. Rewire the Network

A research lab has n computers numbered 0 to n - 1. Each entry [a, b] of connections is a network cable joining computers a and b in both directions; two computers may be joined by several cables. Right now some computers cannot reach others.

In one move you may unplug any cable and use it to join any two computers of your choice. Return the minimum number of moves needed so that every computer can reach every other computer, directly or through other computers. If it is impossible, return -1. If the network is already connected, the answer is 0.

Example 1

Input:
n = 6, connections = [[4,1],[1,2],[2,4],[0,5],[3,0]]
Output:
1
Explanation:

Computers 1, 2 and 4 form a triangle with one spare cable, and 3, 0, 5 form a path. Five cables equal n - 1, and moving the spare cable to join the two groups takes one move.

Example 2

Input:
n = 5, connections = [[3,0],[1,4]]
Output:
-1
Explanation:

Five computers need at least four cables to be connected, but only two exist, so the answer is -1.

Example 3

Input:
n = 8connections = [[0,2],[2,5],[5,6],[6,0],[0,5],[2,6],[0,2]]
Output:
4
Explanation:

Computers 1, 3, 4 and 7 are isolated, while the cluster {0, 2, 5, 6} has seven cables, four more than the three it needs. Four spare cables are moved, one per isolated computer, so the answer is 4.

Constraints

  • 1 ≤ n ≤ 105
  • 0 ≤ connections.length ≤ 105
  • 0 ≤ a, b < n and a ≠ b; the same pair may appear more than once

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 200 msC++ 50 msJava 100 msJavaScript 100 msTypeScript 100 ms

Expected complexity

Time
O((n + m) * alpha(n))
Space
O(n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…