Number of operations to make network connected
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+
- 01Check the necessary cable count first
- 02Union endpoints and ignore edges already in one component
- 03Count distinct roots after all unions
- 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
Hiring now
Visa has 638 open roles right now
landed applies to roles like these for you, on each company’s own site, with answers written for the role.
Senior Director, Greater China Tax
CN - Beijing, China
Sr. Manager, Government Sales Executive
IT - Rome, Italy
Director, Solution Architect, Global Growth Initiatives
GB - London, United Kingdom
Next question