You are given an m × n matrix and need to transform it into a rank matrix where each element is replaced by its relative ranking position.
The ranking system follows these critical rules:
- Ranks start from 1 (not 0)
- Row and column constraints: If two elements are in the same row or column, their relative order must be preserved (smaller value gets smaller rank)
- Equal elements in the same row/column get the same rank
- Minimize ranks: Use the smallest possible rank values
For example, in matrix [[1,2],[3,4]], element 1 gets rank 1, element 2 gets rank 2, but element 3 must get rank 2 (not 3) because it's only larger than elements in its row/column, and element 4 gets rank 3.
Challenge: The tricky part is handling the interconnected constraints across rows and columns simultaneously!
Input & Output
Visualization
Time & Space Complexity
We process each cell once, and Union-Find operations take O(α(mn)) amortized time where α is the inverse Ackermann function
Space for Union-Find structure, row/column rank tracking, and grouping elements by value
Constraints
- m == matrix.length
- n == matrix[i].length
- 1 ≤ m, n ≤ 500
- -109 ≤ matrix[row][col] ≤ 109
- The test cases are generated so that answer is unique under the given rules