- Give each element a component representative.
- Merge representatives when a connection is accepted.
- Answer connectivity or component queries from the compressed representatives.
Code notes
- 41 lines of Python from the credited upstream file 3493.py.
- The implementation visibly relies on sequence storage, ordered lookup.
- 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) -> None:8 i = self._find(u)9 j = self._find(v)10 if i == j:11 return12 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 21 def getCount(self) -> int:22 return self.count23 24 def _find(self, u: int) -> int:25 if self.id[u] != u:26 self.id[u] = self._find(self.id[u])27 return self.id[u]28 29 30class Solution:31 def numberOfComponents(self, properties: list[list[int]], k: int) -> int:32 n = len(properties)33 uf = UnionFind(n)34 propertySets = [set(property) for property in properties]35 36 for i, j in itertools.combinations(range(n), 2):37 if len(propertySets[i] & propertySets[j]) >= k:38 uf.unionByRank(i, j)39 40 return uf.getCount()41