Logo
IconChallenge
Icon
IconProblem
IconSolutions
IconSubmissions

Rank Transform of a Matrix

XPChallenge Points: 30
levelLevel: Hard

You are given a matrix with m rows and n columns. Your task is to create another matrix of the same size, where each cell contains the rank of the value at that position.

A rank is a positive integer that represents the relative order of the value compared to all other numbers in the same row or column. The ranking must follow these conditions:

  • The smallest possible rank is 1.

  • If two cells lie in the same row or column:

    • If one value is smaller, its rank must also be smaller.

    • If both values are equal, their ranks must be equal.

    • If one value is larger, its rank must be larger.

  • The resulting rank matrix must follow all constraints while keeping ranks as small as possible.

  • Input is guaranteed so that there is only one unique valid rank configuration.

Example 1:

Input: matrix = [[2,2,1],[1,2,2]]

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

Explanation:

Equal numbers in the same row/column share the same rank.

Example 2:

Input: matrix = [[4,6],[3,5]]

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

Explanation:

3 is the smallest → rank 1 4 is next → rank 2 5 → rank 2 (same row as 3 but greater) 6 → rank 3

Example 3:

Input: matrix = [[9,3,8],[2,7,6],[1,4,5]]

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

to Continue
like
dislike

Accepted:

Submission:

IconReport an issue
Icon
IconCode
IconYou need toto run or submitYou need toto run or submit
IconTest Case
IconTest Result