Number of Operations to Make Network Connected - Problem

There are n computers numbered from 0 to n - 1 connected by ethernet cables connections forming a network where connections[i] = [ai, bi] represents a connection between computers ai and bi.

Any computer can reach any other computer directly or indirectly through the network. You are given an initial computer network connections. You can extract certain cables between two directly connected computers, and place them between any pair of disconnected computers to make them directly connected.

Return the minimum number of times you need to do this in order to make all the computers connected. If it is not possible, return -1.

Input & Output

Example 1 — Basic Network
$ Input: n = 4, connections = [[0,1],[0,2],[1,2]]
Output: 1
💡 Note: We have 4 computers. Computers 0,1,2 are connected in one group, computer 3 is isolated. We need 1 operation to connect computer 3 to any of the connected computers.
Example 2 — Not Enough Cables
$ Input: n = 6, connections = [[0,1],[0,2]]
Output: -1
💡 Note: We have 6 computers but only 2 cables. To connect all 6 computers, we need at least 5 cables minimum. Since 2 < 5, it's impossible.
Example 3 — Already Connected
$ Input: n = 6, connections = [[0,1],[0,2],[0,3],[1,2],[1,3]]
Output: 2
💡 Note: We have 3 components: {0,1,2,3}, {4}, {5}. We need 2 operations to connect all components into one network.

Constraints

  • 1 ≤ n ≤ 105
  • 1 ≤ connections.length ≤ min(n*(n-1)/2, 105)
  • connections[i].length == 2
  • 0 ≤ connections[i][0], connections[i][1] < n
  • connections[i][0] != connections[i][1]
  • There are no repeated connections.

Visualization

Tap to expand
Network Connected - Union-Find INPUT Network Graph (n=4) 0 1 2 3 [0,1] [0,2] [1,2] Disconnected! n = 4 connections = [ [0,1],[0,2],[1,2] ] ALGORITHM STEPS 1 Check Cable Count cables(3) >= n-1(3)? OK 2 Initialize Union-Find parent[i] = i for each 0 1 2 3 3 Process Connections Union nodes by edges union(0,1) --> {0,1} union(0,2) --> {0,1,2} union(1,2) --> same set 4 Count Components components = 2 {0,1,2} {3} Result = components - 1 = 2 - 1 = 1 FINAL RESULT Before: 2 components 0 1 2 3 Move 1 cable After: 1 component 0 1 2 3 new cable Output: 1 1 operation needed Key Insight: To connect n computers, we need at least n-1 cables. If we have enough cables (>= n-1), the answer is (number of connected components - 1). Extra cables in a component can be moved to connect disconnected components. Union-Find efficiently tracks components in O(n*alpha(n)). TutorialsPoint - Number of Operations to Make Network Connected | Union-Find (Disjoint Set) Approach
Asked in
Microsoft 15 Amazon 12 Google 8
87.2K Views
Medium Frequency
~25 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen