Rank Transform of a Matrix Problem
Description
LeetCode Problem 1632.
Given an m x n matrix, return a new matrix answer where answer[row][col] is the rank of matrix[row][col].
The rank is an integer that represents how large an element is compared to other elements. It is calculated using the following rules:
- The rank is an integer starting from
1. - If two elements
pandqare in the same row or column, then:- If
p < qthenrank(p) < rank(q) - If
p == qthenrank(p) == rank(q) - If
p > qthenrank(p) > rank(q)
- If
- The rank should be as small as possible.
The test cases are generated so that answer is unique under the given rules.
Example 1:

Input: matrix = [[1,2],[3,4]]
Output: [[1,2],[2,3]]
Explanation:
The rank of matrix[0][0] is 1 because it is the smallest integer in its row and column.
The rank of matrix[0][1] is 2 because matrix[0][1] > matrix[0][0] and matrix[0][0] is rank 1.
The rank of matrix[1][0] is 2 because matrix[1][0] > matrix[0][0] and matrix[0][0] is rank 1.
The rank of matrix[1][1] is 3 because matrix[1][1] > matrix[0][1], matrix[1][1] > matrix[1][0], and both matrix[0][1] and matrix[1][0] are rank 2.
Example 2:

Input: matrix = [[7,7],[7,7]]
Output: [[1,1],[1,1]]
Example 3:

Input: matrix = [[20,-21,14],[-19,4,19],[22,-47,24],[-19,4,19]]
Output: [[4,2,3],[1,3,4],[5,1,6],[1,3,4]]
Constraints:
m == matrix.lengthn == matrix[i].length1 <= m, n <= 500-10^9 <= matrix[row][col] <= 10^9
Solution
Approach: Sort by Value + Union-Find
Give ranks from the smallest value up. When we reach a cell, every smaller value in its row and column already has its final rank, so the cell's rank is one more than the largest rank used so far in its row and its column. Keep these in rowMax[i] and colMax[j].
Without equal values, that would be all. Equal values are the tricky case: two equal cells in the same row must get the same rank, and this links further. If matrix[0][0] == matrix[0][3] == matrix[2][3], then (0,0) and (2,3) must share a rank too, even though they share no row or column. So, for each value:
- Put its cells into groups with a union-find over rows and columns (row
iis nodei, columnjis nodem + j). Uniting the row and column of every cell joins all cells that are linked through shared rows or columns. - For each group, take the largest
rowMax/colMaxover all of its cells. The whole group gets that plus one, which is the smallest rank allowed for every cell in it. - Write that rank into the answer and into
rowMaxandcolMaxof the group's rows and columns. - Reset the union-find nodes that were used, so the next value starts with rows and columns apart again.
Complexity: O(mn log(mn)) time for sorting the cells by value; the union-find work is almost linear. O(mn) extra space.
from collections import defaultdict
class UnionFind:
def __init__(self, n):
self.parent = list(range(n))
self.size = [1] * n
def find(self, x):
if self.parent[x] != x:
self.parent[x] = self.find(self.parent[x])
return self.parent[x]
def union(self, a, b):
ra, rb = self.find(a), self.find(b)
if ra == rb:
return
if self.size[ra] < self.size[rb]:
ra, rb = rb, ra
self.parent[rb] = ra
self.size[ra] += self.size[rb]
def reset(self, x):
self.parent[x] = x
self.size[x] = 1
class Solution:
def matrixRankTransform(self, matrix: List[List[int]]) -> List[List[int]]:
m, n = len(matrix), len(matrix[0])
cells = defaultdict(list) # value -> the cells holding it
for i, row in enumerate(matrix):
for j, v in enumerate(row):
cells[v].append((i, j))
row_max = [0] * m # largest rank given so far in each row
col_max = [0] * n # ... and in each column
ans = [[0] * n for _ in range(m)]
uf = UnionFind(m + n) # rows are 0..m-1, columns are m..m+n-1
for v in sorted(cells):
group = cells[v]
# Equal cells linked through a shared row or column must get the same rank.
for i, j in group:
uf.union(i, m + j)
need = {} # component root -> largest rank already used in its rows and columns
for i, j in group:
root = uf.find(i)
need[root] = max(need.get(root, 0), row_max[i], col_max[j])
for i, j in group:
ans[i][j] = row_max[i] = col_max[j] = need[uf.find(i)] + 1
# Split the rows and columns again before the next value.
for i, j in group:
uf.reset(i)
uf.reset(m + j)
return ans