Using Disjoint set(kruskal's Algorithm) //commented code
Code\n\nkr\nclass DisjointSet{\n  \n  public:\n  vector<int>rank,parent;\n  DisjointSet(int n){\n      rank.resize(n+1,0);\n      parent.resize(n+1);\n      for
# Code\n```\nkr\nclass DisjointSet{\n  \n  public:\n  vector<int>rank,parent;\n  DisjointSet(int n){\n      rank.resize(n+1,0);\n      parent.resize(n+1);\n      for(int i=0;i<=n;i++)\n      {\n          parent[i]=i;\n      }\n  }\n  int findup(int n)\n  {\n      if(n==parent[n]) return n;\n      else return parent[n]=findup(parent[n]);\n  }\n\n  void unionbyrank(int u,int v){\n      int ulp_u=findup(u);\n      int ulp_v=findup(v);\n      if(ulp_u==ulp_v) return ;\n      if(rank[ulp_u]<rank[ulp_v]) parent[ulp_u]=ulp_v;\n      else if(rank[ulp_v]<rank[ulp_u]) parent[ulp_v]=ulp_u;\n      else{\n          parent[ulp_v]=ulp_u;\n          rank[ulp_u]++;\n      }\n  }\n};\n\n\nclass Solution {\npublic:\n    int makeConnected(int n, vector<vector<int>>& connections) {\n        DisjointSet ds(n);\n        int extra=0;\n        for(auto it:connections)\n        {\n            int u=it[0];\n            int v=it[1];\n            if(ds.findup(u)==ds.findup(v)) extra++;\n            else{\n                ds.unionbyrank(u,v);\n            }\n        }\n        int ans=0;\n        for(int i=0;i<n;i++)\n        {\n            if(i==ds.parent[i]) ans++;\n        }\n        if(extra>=(ans-1)) return ans-1;\n        return -1;\n    }\n};\n```
['Union Find', 'Minimum Spanning Tree', 'C++']