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 p and q are in the same row or column, then:
    • If p < q then rank(p) < rank(q)
    • If p == q then rank(p) == rank(q)
    • If p > q then rank(p) > rank(q)
  • 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
Rank Transform of a Matrix1234Input MatrixRanking Rules:• Same row/column: p < q → rank(p) < rank(q)• Equal values: rank(p) = rank(q)• Minimize ranks1223Rank Matrix🎯 Key: Value 3 gets rank 2 (not 3) due to column constraint with value 4
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
Asked in
Google 15 Facebook 12 Amazon 8
28.0K Views
Medium Frequency
~35 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen