From 4a877a5d782a4c4e6d437b569d662ae39a5cd174 Mon Sep 17 00:00:00 2001 From: chayan das <110921638+Chayandas07@users.noreply.github.com> Date: Wed, 29 Jan 2025 21:07:50 +0530 Subject: [PATCH] Create 684. Redundant Connection --- 684. Redundant Connection | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 684. Redundant Connection diff --git a/684. Redundant Connection b/684. Redundant Connection new file mode 100644 index 0000000..4c1b51a --- /dev/null +++ b/684. Redundant Connection @@ -0,0 +1,36 @@ +class DisjointSet { +private: + vector 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 findRedundantConnection(vector>& 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 {}; + } +};