- Give each element a component representative.
- Merge representatives when a connection is accepted.
- Answer connectivity or component queries from the compressed representatives.
Code notes
- 59 lines of Python from the credited upstream file 685.py.
- The implementation visibly relies on sequence storage.
- No explicit 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 def __init__(self, n: int):3 self.id = list(range(n))4 self.rank = [0] * n5 6 def unionByRank(self, u: int, v: int) -> bool:7 i = self._find(u)8 j = self._find(v)9 if i == j:10 return False11 if self.rank[i] < self.rank[j]:12 self.id[i] = j13 elif self.rank[i] > self.rank[j]:14 self.id[j] = i15 else:16 self.id[i] = j17 self.rank[j] += 118 return True19 20 def _find(self, u: int) -> int:21 if self.id[u] != u:22 self.id[u] = self._find(self.id[u])23 return self.id[u]24 25 26class Solution:27 def findRedundantDirectedConnection(28 self, edges: list[list[int]],29 ) -> list[int]:30 ids = [0] * (len(edges) + 1)31 nodeWithTwoParents = 032 33 for _, v in edges:34 ids[v] += 135 if ids[v] == 2:36 nodeWithTwoParents = v37 38 def findRedundantDirectedConnection(skippedEdgeIndex: int) -> list[int]:39 uf = UnionFind(len(edges) + 1)40 41 for i, edge in enumerate(edges):42 if i == skippedEdgeIndex:43 continue44 if not uf.unionByRank(edge[0], edge[1]):45 return edge46 47 return []48 49 50 if nodeWithTwoParents == 0:51 return findRedundantDirectedConnection(-1)52 53 for i in reversed(range(len(edges))):54 _, v = edges[i]55 if v == nodeWithTwoParents:56 57 if not findRedundantDirectedConnection(i):58 return edges[i]59