- Give each element a component representative.
- Merge representatives when a connection is accepted.
- Answer connectivity or component queries from the compressed representatives.
Code notes
- 54 lines of Python from the credited upstream file 1579.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.count = n4 self.id = list(range(n))5 self.rank = [0] * n6 7 def unionByRank(self, u: int, v: int) -> bool:8 i = self._find(u)9 j = self._find(v)10 if i == j:11 return False12 if self.rank[i] < self.rank[j]:13 self.id[i] = j14 elif self.rank[i] > self.rank[j]:15 self.id[j] = i16 else:17 self.id[i] = j18 self.rank[j] += 119 self.count -= 120 return True21 22 def _find(self, u: int) -> int:23 if self.id[u] != u:24 self.id[u] = self._find(self.id[u])25 return self.id[u]26 27 28class Solution:29 def maxNumEdgesToRemove(self, n: int, edges: list[list[int]]) -> int:30 alice = UnionFind(n)31 bob = UnionFind(n)32 requiredEdges = 033 34 35 for type_, u, v in sorted(edges, reverse=True):36 u -= 137 v -= 138 if type_ == 3: 39 40 41 42 if alice.unionByRank(u, v) | bob.unionByRank(u, v):43 requiredEdges += 144 elif type_ == 2: 45 if bob.unionByRank(u, v):46 requiredEdges += 147 else: 48 if alice.unionByRank(u, v):49 requiredEdges += 150 51 return (len(edges) - requiredEdges52 if alice.count == 1 and bob.count == 153 else -1)54