- Give each element a component representative.
- Merge representatives when a connection is accepted.
- Answer connectivity or component queries from the compressed representatives.
Code notes
- 65 lines of Python from the credited upstream file 305.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 = [-1] * n4 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 find(self, u: int) -> int:20 if self.id[u] != u:21 self.id[u] = self.find(self.id[u])22 return self.id[u]23 24 25class Solution:26 def numIslands2(27 self,28 m: int,29 n: int,30 positions: list[list[int]],31 ) -> list[int]:32 DIRS = ((0, 1), (1, 0), (0, -1), (-1, 0))33 ans = []34 seen = [[False] * n for _ in range(m)]35 uf = UnionFind(m * n)36 count = 037 38 def getId(i: int, j: int, n: int) -> int:39 return i * n + j40 41 for i, j in positions:42 if seen[i][j]:43 ans.append(count)44 continue45 seen[i][j] = True46 id = getId(i, j, n)47 uf.id[id] = id48 count += 149 for dx, dy in DIRS:50 x = i + dx51 y = j + dy52 if x < 0 or x == m or y < 0 or y == n:53 continue54 neighborId = getId(x, y, n)55 if uf.id[neighborId] == -1: 56 continue57 currentParent = uf.find(id)58 neighborParent = uf.find(neighborId)59 if currentParent != neighborParent:60 uf.unionByRank(currentParent, neighborParent)61 count -= 162 ans.append(count)63 64 return ans65