- Give each element a component representative.
- Merge representatives when a connection is accepted.
- Answer connectivity or component queries from the compressed representatives.
Code notes
- 72 lines of C++ from the credited upstream file 685.cpp.
- The implementation visibly relies on sequence storage.
- 3 loop blocks detected.
Complexity
Account for every find and union operation; with path compression and ranked merging, the amortized cost is nearly constant per operation.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class UnionFind {2 public:3 UnionFind(int n) : id(n), rank(n) {4 iota(id.begin(), id.end(), 0);5 }6 7 bool unionByRank(int u, int v) {8 const int i = find(u);9 const int j = find(v);10 if (i == j)11 return false;12 if (rank[i] < rank[j]) {13 id[i] = j;14 } else if (rank[i] > rank[j]) {15 id[j] = i;16 } else {17 id[i] = j;18 ++rank[j];19 }20 return true;21 }22 23 private:24 vector<int> id;25 vector<int> rank;26 int find(int u) {27 return id[u] == u ? u : id[u] = find(id[u]);28 }29};30 31class Solution {32 public:33 vector<int> findRedundantDirectedConnection(vector<vector<int>>& edges) {34 vector<int> ids(edges.size() + 1);35 int nodeWithTwoParents = 0;36 37 for (const vector<int>& edge : edges) {38 const int v = edge[1];39 if (++ids[v] == 2) {40 nodeWithTwoParents = v;41 break;42 }43 }44 45 46 if (nodeWithTwoParents == 0)47 return findRedundantDirectedConnection(edges, -1);48 49 for (int i = edges.size() - 1; i >= 0; --i)50 if (edges[i][1] == nodeWithTwoParents)51 52 if (findRedundantDirectedConnection(edges, i).empty())53 return edges[i];54 55 throw;56 }57 58 vector<int> findRedundantDirectedConnection(const vector<vector<int>>& edges,59 int skippedEdgeIndex) {60 UnionFind uf(edges.size() + 1);61 62 for (int i = 0; i < edges.size(); ++i) {63 if (i == skippedEdgeIndex)64 continue;65 if (!uf.unionByRank(edges[i][0], edges[i][1]))66 return edges[i];67 }68 69 return {};70 }71};72