Problem solution · Python

Rank Transform of a Matrix

Rank Transform of a Matrix: a Python solution using disjoint set union. Learn the idea, check the complexity, and read the full code, with credit to walkccc LeetCode Solutions.

Technique
Disjoint set union
Source
walkccc LeetCode Solutions
Length
54 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Disjoint set union

For Rank Transform of a Matrix, the implementation maintains connected components and merges them as relationships are processed.

  1. Give each element a component representative.
  2. Merge representatives when a connection is accepted.
  3. 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.

Source

Code and credit

This code comes from walkccc LeetCode Solutions by P.-Y. Chen (walkccc) and is used under the MIT licence.

Full codeRank Transform of a Matrix · PythonPython
Use this to learn the idea, then write your own version.
class UnionFind:  def __init__(self):    self.id = {}   def union(self, u: int, v: int) -> None:    self.id.setdefault(u, u)    self.id.setdefault(v, v)    i = self._find(u)    j = self._find(v)    if i != j:      self.id[i] = j   def getGroupIdToValues(self) -> dict[int, list[int]]:    groupIdToValues = collections.defaultdict(list)    for u in self.id.keys():      groupIdToValues[self._find(u)].append(u)    return groupIdToValues   def _find(self, u: int) -> int:    if self.id[u] != u:      self.id[u] = self._find(self.id[u])    return self.id[u]  class Solution:  def matrixRankTransform(self, matrix: list[list[int]]) -> list[list[int]]:    m = len(matrix)    n = len(matrix[0])    ans = [[0] * n for _ in range(m)]    # {val: [(i, j)]}    valToGrids = collections.defaultdict(list)    # rank[i] := the maximum rank of the row or column so far    maxRankSoFar = [0] * (m + n)     for i, row in enumerate(matrix):      for j, val in enumerate(row):        valToGrids[val].append((i, j))     for _, grids in sorted(valToGrids.items()):      uf = UnionFind()      for i, j in grids:        # Union i-th row with j-th col.        uf.union(i, j + m)      for values in uf.getGroupIdToValues().values():        # Get the maximum rank of all the included rows and columns.        maxRank = max(maxRankSoFar[i] for i in values)        for i in values:          # Update all the rows and columns to maxRank + 1.          maxRankSoFar[i] = maxRank + 1      for i, j in grids:        ans[i][j] = maxRankSoFar[i]     return ans 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗