Skip to content

Commit

Permalink
Create 684. Redundant Connection (#700)
Browse files Browse the repository at this point in the history
  • Loading branch information
Chayandas07 authored Jan 29, 2025
2 parents 2fb6164 + 4a877a5 commit c96ae85
Showing 1 changed file with 36 additions and 0 deletions.
36 changes: 36 additions & 0 deletions 684. Redundant Connection
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
class DisjointSet {
private:
vector<int> parent;
public:
DisjointSet(int n) {
parent.resize(n+1);
for (int i = 1; i < n + 1; ++i) {
parent[i] = i; //initially all nodes are set as independent
}
}
int find(int u) {
if (parent[u] == u) return u;
return parent[u] = find(parent[u]);
}
bool Union(int u, int v) {
int parU = find(u);
int parV = find(v);
if (parU != parV) { // not part of the set yet
parent[parV] = parU;
return true;
} else return false; // already part of the set

}
};
class Solution {
public:
vector<int> findRedundantConnection(vector<vector<int>>& edges) {
int n = edges.size(); //here graphs with n nodes have n edges
DisjointSet ds(n);
for (const auto &edge : edges) {
int u = edge[1], v = edge[0];
if (!ds.Union(u, v)) return edge;
}
return {};
}
};

0 comments on commit c96ae85

Please sign in to comment.