 All Problems
Number of Operations to Make Network Connected
medium
union-find
graph
amazon
google

There are n computers numbered 0 to n-1 connected by some cables. You can extract a cable between directly connected computers and place it between any two disconnected ones.

Given connections, return the minimum number of cable operations needed to make all computers connected, or -1 if impossible.

Example 1:

Input: n = 4, connections = [[0,1],[0,2],[1,2]]
Output: 1

Example 2:

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

Constraints:

  • 1 <= n <= 10^5
  • 1 <= connections.length <= min(n*(n-1)/2, 10^5)
Run to check your code against the sample cases, or submit to run every case