#1632

Rank Transform of a Matrix

Hard
ArrayUnion-FindGraph TheoryTopological SortSortingMatrixHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(m * n * m * n)
O(m * n log(m * n))
Space
O(1)
O(m * n)
💡

Intuition

Time O(m * n log(m * n))Space O(m * n)

In the optimal solution, we will sort the elements and assign ranks based on their positions in the sorted order, while keeping track of the maximum rank in their respective rows and columns. This is more efficient than the brute force approach.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a list of tuples containing each element's value and its coordinates (row, col).
  2. 2Step 2: Sort this list based on the values of the elements.
  3. 3Step 3: Iterate through the sorted list and for each element, calculate its rank based on the maximum rank in its row and column, updating the result matrix accordingly.
solution.py16 lines
1# Full working Python code
2
3def rankTransform(matrix):
4    m, n = len(matrix), len(matrix[0])
5    result = [[0] * n for _ in range(m)]
6    elements = [(matrix[i][j], i, j) for i in range(m) for j in range(n)]
7    elements.sort()
8    row_rank = [0] * m
9    col_rank = [0] * n
10    
11    for value, i, j in elements:
12        rank = max(row_rank[i], col_rank[j]) + 1
13        result[i][j] = rank
14        row_rank[i] = rank
15        col_rank[j] = rank
16    return result

Complexity note: The complexity is dominated by the sorting step, which is O(m * n log(m * n)), where m * n is the total number of elements in the matrix.

  • 1Sorting elements allows for efficient rank assignment.
  • 2Maintaining row and column ranks helps to derive the correct rank without redundant comparisons.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.