- 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 1632.py.
- The implementation visibly relies on sequence storage, hash 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):3 self.id = {}4 5 def union(self, u: int, v: int) -> None:6 self.id.setdefault(u, u)7 self.id.setdefault(v, v)8 i = self._find(u)9 j = self._find(v)10 if i != j:11 self.id[i] = j12 13 def getGroupIdToValues(self) -> dict[int, list[int]]:14 groupIdToValues = collections.defaultdict(list)15 for u in self.id.keys():16 groupIdToValues[self._find(u)].append(u)17 return groupIdToValues18 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 matrixRankTransform(self, matrix: list[list[int]]) -> list[list[int]]:27 m = len(matrix)28 n = len(matrix[0])29 ans = [[0] * n for _ in range(m)]30 31 valToGrids = collections.defaultdict(list)32 33 maxRankSoFar = [0] * (m + n)34 35 for i, row in enumerate(matrix):36 for j, val in enumerate(row):37 valToGrids[val].append((i, j))38 39 for _, grids in sorted(valToGrids.items()):40 uf = UnionFind()41 for i, j in grids:42 43 uf.union(i, j + m)44 for values in uf.getGroupIdToValues().values():45 46 maxRank = max(maxRankSoFar[i] for i in values)47 for i in values:48 49 maxRankSoFar[i] = maxRank + 150 for i, j in grids:51 ans[i][j] = maxRankSoFar[i]52 53 return ans54