Taro Logo

Rank Transform of a Matrix

Hard
Asked by:
Google
Meta
Citadel
Glean
144 views
Topics:
ArraysGraphsDynamic Programming

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.

Example 1:

Input: matrix = [[1,2],[3,4]]
Output: [[1,2],[2,3]]
Explanation:
The rank of matrix[0][0] is 1 because it is the smallest integer in its row and column.
The rank of matrix[0][1] is 2 because matrix[0][1] > matrix[0][0] and matrix[0][0] is rank 1.
The rank of matrix[1][0] is 2 because matrix[1][0] > matrix[0][0] and matrix[0][0] is rank 1.
The rank of matrix[1][1] is 3 because matrix[1][1] > matrix[0][1], matrix[1][1] > matrix[1][0], and both matrix[0][1] and matrix[1][0] are rank 2.

Example 2:

Input: matrix = [[7,7],[7,7]]
Output: [[1,1],[1,1]]

Example 3:

Input: matrix = [[20,-21,14],[-19,4,19],[22,-47,24],[-19,4,19]]
Output: [[4,2,3],[1,3,4],[5,1,6],[1,3,4]]

Constraints:

  • m == matrix.length
  • n == matrix[i].length
  • 1 <= m, n <= 500
  • -109 <= matrix[row][col] <= 109

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What are the constraints on the dimensions of the matrix ($m imes n$), and what are the value ranges of the elements inside it?
  2. How should identical values within the same row or column be ranked relative to each other? For example, if the same number appears twice in the same row, must they always receive the exact same rank?
  3. If multiple identical values form a chain or cycle of dependencies across intersecting rows and columns (e.g., $A$ is in the same row as $B$ and same column as $C$), how should those transitive relationships be resolved?
  4. Is the input matrix guaranteed to be non-empty, and can it contain negative numbers or zeros?
  5. If there are multiple valid rank transform matrices that satisfy the relative ordering rules, does the interviewer expect a specific canonical output, or is any valid ranking acceptable?

Brute Force Solution

Approach

Imagine you have a grid filled with numbers and you need to replace every single number with a rank based on how big it is compared to others in the same row and column. The brute force approach involves starting with the smallest possible ranks and exhaustively trying different numbers for every single spot in the grid until you find a valid set of ranks that follows all the ordering rules.

Here's how the algorithm would work step-by-step:

  1. Start by looking at the entire grid of numbers to find the smallest value present.
  2. Assign a starting rank of one to that smallest value.
  3. Look at every other position in the grid and try assigning different ranks, checking every possible combination of ranks one by one.
  4. For every combination you try, check if the numbers in the same row and the same column still keep their correct order from smallest to largest.
  5. If a combination breaks the rule where a larger number must have a larger rank than a smaller number in the same row or column, throw that combination away.
  6. Keep trying different ranks for every position until you find a complete set of ranks that satisfies every single row and column ordering rule without violating any conditions.

Code Implementation

def matrix_rank_transform(matrix):
    row_count = len(matrix)
    column_count = len(matrix[0])
    
    # Generate all possible rank assignments to exhaustively test every combination
    from itertools import product
    unique_values = sorted(list(set(cell for row in matrix for cell in row)))
    
    def validate_ranking(current_ranking):
        # Verify row and column ordering constraints are strictly maintained
        for row_index in range(row_count):
            for column_index in range(column_count):
                for other_column in range(column_index + 1, column_count):
                    if matrix[row_index][column_index] < matrix[row_index][other_column]:
                        if current_ranking[row_index][column_index] >= current_ranking[row_index][other_column]:
                            return False
                    elif matrix[row_index][column_index] > matrix[row_index][other_column]:
                        if current_ranking[row_index][column_index] <= current_ranking[row_index][other_column]:
                            return False
                    elif matrix[row_index][column_index] == matrix[row_index][other_column]:
                        if current_ranking[row_index][column_index] != current_ranking[row_index][other_column]:
                            return False
                            
        for column_index in range(column_count):
            for row_index in range(row_count):
                for other_row in range(row_index + 1, row_count):
                    if matrix[row_index][column_index] < matrix[other_row][column_index]:
                        if current_ranking[row_index][column_index] >= current_ranking[other_row][column_index]:
                            return False
                    elif matrix[row_index][column_index] > matrix[other_row][column_index]:
                        if current_ranking[row_index][column_index] <= current_ranking[other_row][column_index]:
                            return False
                    elif matrix[row_index][column_index] == matrix[other_row][column_index]:
                        if current_ranking[row_index][column_index] != current_ranking[other_row][column_index]:
                            return False
        return True

    max_possible_rank = row_count * column_count
    rank_choices = range(1, max_possible_rank + 1)
    
    # Iterate through every rank combination until a valid grid configuration emerges
    for candidate_flat in product(rank_choices, repeat=row_count * column_count):
        candidate_grid = []
        for row_index in range(row_count):
            start_index = row_index * column_count
            end_index = start_index + column_count
            candidate_grid.append(list(candidate_flat[start_index:end_index]))
            
        if validate_ranking(candidate_grid):
            return candidate_grid
            
    return matrix

Big(O) Analysis

Time Complexity
O(b^(r*c)) – Given a grid with r rows and c columns containing a total of n cells, the brute force approach exhaustively tries different rank combinations for every single cell. For each cell, we explore a branching factor of possible rank values up to the total number of unique values, bounded by the grid size. As we check every combination across all r times c positions, the total operations grow exponentially like b to the power of (r times c), which simplifies to an exponential time complexity of O(b^(r*c)).
Space Complexity
O(r * c) – To determine the valid rank combinations described in the exhaustive search, the algorithm requires temporary variables to track every possible rank assignment across the entire grid. Specifically, it maintains auxiliary state storage for the current rank configuration of size r times c, where r and c are the dimensions of the grid and the total number of elements is N. As the input size N grows, the memory required to store these intermediate ranking combinations and validation states scales linearly with the total number of grid cells. Therefore, substituting the grid dimensions with N results in a total auxiliary space complexity of O(N).

Optimal Solution

Approach

To find the rank transform of a grid, the optimal strategy processes numbers from smallest to largest by grouping identical values together. It then uses a clever connection-tracking tool to figure out which numbers share a row or column, ensuring that numbers in the same row or column respect their relative order.

Here's how the algorithm would work step-by-step:

  1. Gather all the numbers in the grid and sort them from smallest to largest so you can handle them in the correct sequence.
  2. Group identical numbers together because they will share the exact same rank if they happen to live in the same row or column.
  3. For each group, look at which rows and columns the numbers belong to, and connect rows and columns that share a number from this group.
  4. Use a grouping tool to find connected components of rows and columns, which tells you which rows and columns must be evaluated together.
  5. For each connected component, determine the current maximum rank found so far in each of its participating rows and columns.
  6. Calculate the new rank for each number in the group by looking at the highest rank in its connected row or column, and add one to that highest value.
  7. Update the tracking records with these new ranks so future numbers in later groups know how high they can climb.
  8. Repeat this process for every group of numbers from smallest to largest until the entire grid is successfully filled with rank values.

Code Implementation

class DisjointSetUnion:
    def __init__(self, total_elements):
        self.parent_pointers = list(range(total_elements))

    def find_set_root(self, element):
        if self.parent_pointers[element] != element:
            self.parent_pointers[element] = self.find_set_root(self.parent_pointers[element])
        return self.parent_pointers[element]

    def union_sets(self, first_element, second_element):
        root_first = self.find_set_root(first_element)
        root_second = self.find_set_root(second_element)
        if root_first != root_second:
            self.parent_pointers[root_first] = root_second


class Solution:
    def matrixRankTransform(self, matrix: list[list[int]]) -> list[list[int]]:
        row_count = len(matrix)
        col_count = len(matrix[0])
        value_to_coordinates = {}

        for row_index in range(row_count):
            for col_index in range(col_count):
                cell_value = matrix[row_index][col_index]
                if cell_value not in value_to_coordinates:
                    value_to_coordinates[cell_value] = []
                value_to_coordinates[cell_value].append((row_index, col_index))

        max_rank_in_row = [0] * row_count
        max_rank_in_col = [0] * col_count
        result_matrix = [[0] * col_count for _ in range(row_count)]

        # Process identical values in order so lower ranks are fully established first.
        for cell_value in sorted(value_to_coordinates.keys()):
            coordinates_list = value_to_coordinates[cell_value]
            disjoint_set = DisjointSetUnion(row_count + col_count)

            for row_index, col_index in coordinates_list:
                disjoint_set.union_sets(row_index, col_count + col_index)

            component_groups = {}
            for row_index, col_index in coordinates_list:
                component_root = disjoint_set.find_set_root(row_index)
                if component_root not in component_groups:
                    component_groups[component_root] = []
                component_groups[component_root].append((row_index, col_index))

            # Group interdependent rows and columns sharing identical values together.
            for component_root, group_coords in component_groups.items():
                maximum_component_rank = 0
                for row_index, col_index in group_coords:
                    maximum_component_rank = max(maximum_component_rank, max_rank_in_row[row_index], max_rank_in_col[col_index])

                for row_index, col_index in group_coords:
                    result_matrix[row_index][col_index] = maximum_component_rank + 1

                # Synchronize maximum ranks across all connected rows and columns.
                for row_index, col_index in group_coords:
                    max_rank_in_row[row_index] = maximum_component_rank + 1
                    max_rank_in_col[col_index] = maximum_component_rank + 1

        return result_matrix

Big(O) Analysis

Time Complexity
O(mn log(mn)) – Given a matrix of size m by n with total elements T = m * n, the primary cost is gathering and sorting all T elements from smallest to largest, which takes O(T log T) time. Grouping the sorted values and processing each unique value through the connected components union-find structure takes nearly linear time relative to T. Across all groups, the row and column unions and rank updates perform nearly constant time operations per element. Combining the sorting dominance T log T with m and n dimensions results in O(mn log(mn)) total operations.
Space Complexity
O(m * n + m + n) – The space complexity is driven by several auxiliary data structures required to process the grid. Specifically, a list or hash map stores all m times n matrix elements grouped by their values, while additional tracking arrays store the maximum ranks for each of the m rows and n columns. Union-find parent arrays and component lists further require memory proportional to the sum of m rows and n columns. Combining these structures yields a total auxiliary space complexity of O(m * n + m + n).

Edge Cases

Empty matrix or matrix with empty rows
How to Handle:
Return the empty matrix immediately as no ranks can be computed.
Single element matrix
How to Handle:
Return a matrix containing a single 1 since the minimum rank is always 1.
Matrix with all identical values
How to Handle:
All elements must be grouped together via union-find and assigned a rank of 1.
Duplicate values within the same row or column
How to Handle:
Connect these identical values using a disjoint-set data structure so they share the exact same rank.
Negative numbers and mixed signs
How to Handle:
Sort all distinct matrix values globally to ensure negative numbers correctly receive smaller ranks than positive ones.
Chained dependencies forming paths across rows and columns
How to Handle:
Process values in strictly increasing order while tracking the maximum rank assigned to each row and column index.
Extremely large matrices up to maximum constraints
How to Handle:
Use an optimized sorting and union-find approach to prevent time limit exceed errors.
Extreme integer values at boundary limits
How to Handle:
Rely on relative magnitude sorting of values rather than their absolute values to avoid any overflow issues.