Number of Operations to Make Network Connected

There are n computers numbered 0 to n - 1 joined by ethernet cables, where connections[i] = [a, b] links computers a and b. Any computer can reach any other through the network directly or indirectly. In one operation you may unplug a cable between two directly connected computers and plug it between any pair of disconnected computers. Return the minimum number of operations needed to connect all the computers, or -1 if it is not possible.

30:00

Number of Operations to Make Network Connected
medium
Free written solution
Topics
Companies

There are n computers numbered 0 to n - 1 joined by ethernet cables, where connections[i] = [a, b] links computers a and b. Any computer can reach any other through the network directly or indirectly. In one operation you may unplug a cable between two directly connected computers and plug it between any pair of disconnected computers. Return the minimum number of operations needed to connect all the computers, or -1 if it is not possible.

Example 1:
Input: {"n":4,"connections":[[0,1],[0,2],[1,2]]}
Output: 1
Constraints:
  • 1≤n≤1051 \leq n \leq 10^5

  • 1≤connections.length≤min⁡(n(n−1)/2,105)1 \leq \text{connections.length} \leq \min(n(n-1)/2, 10^5)

  • connections[i].length==2\text{connections}[i].\text{length} == 2

  • 0≤ai,bi<n0 \leq a_i, b_i < n

  • ai≠bia_i \neq b_i

  • There are no repeated connections and no two computers are connected by more than one cable.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"n":4,"connections":[[0,1],[0,2],[1,2]]}

There are 4 computers and 3 cables. To link n computers into one network we need at least n - 1 = 3 cables.

0-1

0-2

1-2

0123

cables / needed

3 / 3

groups

4

spare cables

0

Variables
VariableValue
n4
cables3
components4
spare0
DepthFunction Call
Stack empty
0/7