LC 684 - Redundant Connection

Approach This is a typical union find method, we can union and get parent with amortized O(1) complexity, and when we find the two nodes are already having the same parent, return the answer (this form a loop). Code class Solution { public: struct UnionFind { UnionFind(int n) { parent.assign(n, 0); for(int i = 0 ; i < n ; ++i) parent[i] = i; sz.assign(n, 1); } int GetParent(int a) { if(parent[a] != a) parent[a] = GetParent(parent[a]); return parent[a]; } bool Union(int a, int b) { a = GetParent(a); b = GetParent(b); if(a == b) return false; if(sz[a] < sz[b]) swap(a, b); sz[a] += sz[b]; parent[b] = a; return true; } vector<int> parent; vector<int> sz; }; vector<int> findRedundantConnection(vector<vector<int>>& edges) { UnionFind uf(edges.size() + 1); for(const auto& e: edges) { if(!uf.Union(e[0],e[1])) return {e[0], e[1]}; } return {}; } };

January 27, 2026 · 1 min

LC 1319 - Number of Operations to Make Network Connected

Approach This is also a union find problem, but I was wrong in the beginning. I though we could merge the first two first, and then keep track of the unconncted nodes, and then check if we have enough resource to connect them one by one. But actually, the unconnected nodes might itself become clustered and we don’t really need to conenct them ony by one. Therefore the correct approach is to merge all of them first, and collect the number of extra edges. Also, we check the number of compoenets comp in the end of merging, and we know that we would need comp-1 more extra edge to merge all the components. ...

January 27, 2026 · 2 min