- Give each element a component representative.
- Merge representatives when a connection is accepted.
- Answer connectivity or component queries from the compressed representatives.
Code notes
- 57 lines of Python from the credited upstream file 2092.py.
- The implementation visibly relies on sequence storage, hash lookup, 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.id = list(range(n))4 self.rank = [0] * n5 6 def unionByRank(self, u: int, v: int) -> None:7 i = self._find(u)8 j = self._find(v)9 if i == j:10 return11 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 19 def connected(self, u: int, v: int) -> bool:20 return self._find(self.id[u]) == self._find(self.id[v])21 22 def reset(self, u: int) -> None:23 self.id[u] = u24 25 def _find(self, u: int) -> int:26 if self.id[u] != u:27 self.id[u] = self._find(self.id[u])28 return self.id[u]29 30 31class Solution:32 def findAllPeople(33 self,34 n: int,35 meetings: list[list[int]],36 firstPerson: int,37 ) -> list[int]:38 uf = UnionFind(n)39 timeToPairs = collections.defaultdict(list)40 41 uf.unionByRank(0, firstPerson)42 43 for x, y, time in meetings:44 timeToPairs[time].append((x, y))45 46 for _, pairs in sorted(timeToPairs.items(), key=lambda x: x[0]):47 peopleUnioned = set()48 for x, y in pairs:49 uf.unionByRank(x, y)50 peopleUnioned.add(x)51 peopleUnioned.add(y)52 for person in peopleUnioned:53 if not uf.connected(person, 0):54 uf.reset(person)55 56 return [i for i in range(n) if uf.connected(i, 0)]57