KatInterview

Assign Minimum Consistent Ranks to Matrix Cells

Arrays & HashingAuto-graded · 23 test cases
MediumAuto-gradedArrays & Hashingsortinggreedymatrix

Last updated

Tests greedy assignment of ranks by processing elements in sorted order while maintaining row and column constraints.

Given an m x n matrix containing distinct integers, assign each cell a rank (positive integer) following these rules:

  • Ranks start at 1
  • Within any row or column, a cell holding a larger value must receive a strictly larger rank than cells with smaller values
  • Subject to the above constraints, every rank should be as small as possible

Return a matrix of the same dimensions where each cell contains its assigned rank.

Since all values in the input are distinct, there is exactly one valid ranking.

Constraints

  • 1 <= m, n <= 500
  • m * n <= 10^5
  • -10^9 <= matrix[i][j] <= 10^9
  • All values in the matrix are distinct

Examples

Example 1

Input: assign_ranks([[10, 40, 20, 30]])

Output: [[1, 4, 2, 3]]

Example 2

Input: assign_ranks([[1, 5], [4, 2]])

Output: [[1, 2], [2, 1]]

Example 3

Input: assign_ranks([[3, 1, 9], [8, 2, 7], [4, 6, 5]])

Output: [[2, 1, 6], [6, 2, 5], [3, 5, 4]]

Hints

Hint 1

Consider processing cells in sorted order by their values. What information do you need to track?

Hint 2

For each row and column, track the highest rank assigned so far. When you process a cell, how does this help determine its rank?

Hint 3

Because values are distinct and processed in increasing order, the most recent rank in a row or column is always the maximum for that row or column.