Number of operations to make network connected

Asked atVisa
1Give yourself 5 minutes
2Answer out loud, not in your head
3Then compare with the answer below

The problem

Given a graph with n vertices and m edges. The graph is represented by an array Edges, where Edge[i] = [a, b] indicates an edge between vertices a and b. One edge can be removed from anywhere and added between any two vertices in one operation. Find the minimum number of operations that will be required to make the graph connected. If it is not possible to make the graph connected, return -1.

**Input : **n = 4, Edge =[ [0, 1], [ 0, 2], [1, 2]]

Output: 1 Explanation: We need a minimum of 1 operation to make the two components connected. We can remove the edge (1,2) and add the edge between node 2 and node 3 like the following:

Input: n = 9, Edge = [[0,1],[0,2],[0,3],[1,2],[2,3],[4,5],[5,6],[7,8]]

**Output: **2 Explanation: We need a minimum of 2 operations to make the two components connected. We can remove the edge (0,2) and add the edge between node 3 and node 4 and we can remove the edge (0,3) and add it between nodes 6 and 8 like the following:

Input: n = 4, Edge =[[0, 1]]

  • 1 <= n <= 104
  • 1 <= Edge.length <= 104
  • Edge[i].length == 2

cpp

class Solution{
public:
    int solve(int n, vector<vector<int>> &Edge){
        
    }
};

java

class Solution {
    public int solve(int n, int[][] Edge) {
      
    }
}

python

class Solution:
    def solve(self, n, Edge):

javascript

class Solution {
    solve(n, Edge) {
        
    }
}

csharp

public class Solution {
    public int solve(int n, List<int[]> Edge) {
        
    }
}

go

func solve(n int, edges [][]int) int {

}
Stuck? Show a way to structure it+
  1. 01Check the necessary cable count first
  2. 02Union endpoints and ignore edges already in one component
  3. 03Count distinct roots after all unions
  4. 04Return components minus one

Reference answer

Then expect these follow-ups

  • Why is n-1 a necessary threshold?

    Tests: correctness reasoning

  • How would you return the actual rewiring operations?

    Tests: implementation extension

Free to read · better with Enzo

Practice this out loud with Enzo

Enzo runs it as a mock interview, pushes back with follow-ups, and grades you on the rubric.

Next question