Rank Transform of a Matrix - Problem
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.
Input & Output
Example 1 — Basic Matrix
$
Input:
matrix = [[1,2],[3,4]]
›
Output:
[[1,2],[2,3]]
💡 Note:
Value 1 gets rank 1, value 2 gets rank 2, value 3 gets rank 2 (constrained by row/column), value 4 gets rank 3
Example 2 — Equal Elements
$
Input:
matrix = [[7,7],[7,7]]
›
Output:
[[1,1],[1,1]]
💡 Note:
All elements have the same value, so they all get rank 1
Example 3 — Complex Constraints
$
Input:
matrix = [[20,-21,14],[-19,4,19],[22,-47,24]]
›
Output:
[[4,2,3],[1,5,6],[6,1,7]]
💡 Note:
Ranks assigned respecting row and column ordering constraints while keeping them as small as possible
Constraints
- m == matrix.length
- n == matrix[i].length
- 1 ≤ m, n ≤ 500
- -109 ≤ matrix[row][col] ≤ 109
Visualization
Tap to expand
Understanding the Visualization
1
Input Matrix
Matrix with values that need ranking
2
Apply Constraints
Rank elements respecting row/column ordering
3
Output Ranks
Minimum possible ranks maintaining all constraints
Key Takeaway
🎯 Key Insight: Equal elements in same row/column form connected components that must share the same rank
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code