Ctrl K

Cell Levels by Rows and Columns

Hard
You are given an m × n table grid. Assign every cell a level, an integer starting from 1, so that for any two cells p and q that share a row or a column: - if grid[p] < grid[q], the level of p is smaller than the level of q; - if grid[p] == grid[q], their levels are equal; - if grid[p] > grid[q], the level of p is larger than the level of q. Cells that share neither a row nor a column do not constrain each other. Levels must be as small as possible; under these rules that assignment is unique. Return a table of the same size holding each cell's level.
Example 1
grid=[[5, 1], [5, 9]] → [[2, 1], [2, 3]]

1 is the smallest in its row and column, so it gets level 1. Both 5s share a column and are equal, so they share a level; the top 5 is larger than the 1 in its row, so that level is 2. The 9 exceeds the 5 in its row and the 1 in its column, so it gets level 3.

Example 2
grid=[[4, 4, 4]] → [[1, 1, 1]]

All values are equal and share a row, so every cell gets level 1.

Example 3
grid=[[3, -2, 8], [7, 3, 0], [-2, 6, 3]] → [[2, 1, 3], [3, 2, 1], [1, 3, 2]]
Constraints
  • 1 ≤ m, n ≤ 500
  • -10⁹ ≤ grid[i][j] ≤ 10⁹
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsCompress a Grid of Numbers HardLongest Uphill Walk HardEach Color Once HardScooter Trips Under a Road Limit HardMouse, Cat and Cheese Hard
loading Python…
Input
grid=[[5, 1], [5, 9]]
Expected
[[2, 1], [2, 3]]

Run checks the first 3 tests in your browser. Submit checks all 99 tests on the server, hidden ones included.