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:
1.p and q are in the same row or column, then:
p < q then rank(p) < rank(q)p == q then rank(p) == rank(q)p > q then rank(p) > rank(q)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.lengthn == matrix[i].length1 <= m, n <= 500-109 <= matrix[row][col] <= 109When 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:
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:
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 matrixTo 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:
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| Case | How to Handle |
|---|---|
| Empty matrix or matrix with empty rows | Return the empty matrix immediately as no ranks can be computed. |
| Single element matrix | Return a matrix containing a single 1 since the minimum rank is always 1. |
| Matrix with all identical values | All elements must be grouped together via union-find and assigned a rank of 1. |
| Duplicate values within the same row or column | Connect these identical values using a disjoint-set data structure so they share the exact same rank. |
| Negative numbers and mixed signs | 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 | 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 | Use an optimized sorting and union-find approach to prevent time limit exceed errors. |
| Extreme integer values at boundary limits | Rely on relative magnitude sorting of values rather than their absolute values to avoid any overflow issues. |