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 Matrix INPUT MATRIX 1 2 3 4 [0,0] [0,1] [1,0] [1,1] matrix = [[1,2],[3,4]] 2x2 matrix, all unique Sorted: 1 < 2 < 3 < 4 Process in this order ALGORITHM STEPS 1 Group by Value Sort cells, group equals 2 Union-Find Unite same row/col equals 3 Track Max Rank Per row/col constraints 4 Assign Ranks max(row,col rank) + 1 Processing Order: 1 at [0,0]: rank = 1 2 at [0,1]: max(row0=1) + 1 = 2 3 at [1,0]: max(col0=1) + 1 = 2 4 at [1,1]: max(row1=2,col1=2)+1=3 FINAL RESULT 1 2 2 3 rank 1 rank 2 rank 2 rank 3 [[1,2],[2,3]] Verification: OK Row 0: 1 < 2 (OK) Col 0: 1 < 2, Col 1: 2 < 3 (OK) Key Insight: Union-Find groups equal values in same row/column, ensuring they get the same rank. Processing values in sorted order with row/column max tracking guarantees minimal valid ranks. Time: O(m*n*log(m*n)) for sorting, Space: O(m*n) for Union-Find structure. TutorialsPoint - Rank Transform of a Matrix | Union-Find with Topological Sort
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