MCPcopy Create free account
hub / github.com/Tiwarishashwat/InterviewCodes / Solution

Class Solution

NumberOfOperationsToMakeNetworkConnected.java:1–20  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

1class Solution {
2 public int makeConnected(int n, int[][] connections) {
3 //atleast n-1 edges are required to connect all nodes into a single component
4 if(connections.length < n-1){
5 return -1;
6 }
7 int wires=0;
8 DisjointSet dsu = new DisjointSet(n);
9 for(int connection[] : connections){
10 int u = connection[0];
11 int v = connection[1];
12 if(dsu.unionBySize(u,v)){
13 wires++;
14 }
15 }
16 //for connecting n nodes, we require a minimum of n-1 edges
17 // so minimum wires requires = (n-1) - (wires-used)
18 return n-1-wires;
19 }
20}
21
22public class DisjointSet {
23 int parent[];

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected