Problem solution · C++

Redundant Connection II

Redundant Connection II: a C++ solution using disjoint set union. Learn the idea, check the complexity, and read the full code, with credit to walkccc LeetCode Solutions.

Technique
Disjoint set union
Source
walkccc LeetCode Solutions
Length
72 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Disjoint set union

For Redundant Connection II, the implementation maintains connected components and merges them as relationships are processed.

  1. Give each element a component representative.
  2. Merge representatives when a connection is accepted.
  3. 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.

Source

Code and credit

This code comes from walkccc LeetCode Solutions by P.-Y. Chen (walkccc) and is used under the MIT licence.

Full codeRedundant Connection II · C++C++
Use this to learn the idea, then write your own version.
class UnionFind { public:  UnionFind(int n) : id(n), rank(n) {    iota(id.begin(), id.end(), 0);  }   bool unionByRank(int u, int v) {    const int i = find(u);    const int j = find(v);    if (i == j)      return false;    if (rank[i] < rank[j]) {      id[i] = j;    } else if (rank[i] > rank[j]) {      id[j] = i;    } else {      id[i] = j;      ++rank[j];    }    return true;  }  private:  vector<int> id;  vector<int> rank;  int find(int u) {    return id[u] == u ? u : id[u] = find(id[u]);  }}; class Solution { public:  vector<int> findRedundantDirectedConnection(vector<vector<int>>& edges) {    vector<int> ids(edges.size() + 1);    int nodeWithTwoParents = 0;     for (const vector<int>& edge : edges) {      const int v = edge[1];      if (++ids[v] == 2) {        nodeWithTwoParents = v;        break;      }    }     // If there is no edge with two ids, don't skip any edge.    if (nodeWithTwoParents == 0)      return findRedundantDirectedConnection(edges, -1);     for (int i = edges.size() - 1; i >= 0; --i)      if (edges[i][1] == nodeWithTwoParents)        // Try to delete the edges[i].        if (findRedundantDirectedConnection(edges, i).empty())          return edges[i];     throw;  }   vector<int> findRedundantDirectedConnection(const vector<vector<int>>& edges,                                              int skippedEdgeIndex) {    UnionFind uf(edges.size() + 1);     for (int i = 0; i < edges.size(); ++i) {      if (i == skippedEdgeIndex)        continue;      if (!uf.unionByRank(edges[i][0], edges[i][1]))        return edges[i];    }     return {};  }}; 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗