KatInterview

Rank Anti-Diagonal Strings of a Letter Grid

Heaps, Sorting & SearchAuto-graded · 17 test cases
MediumAuto-gradedHeaps, Sorting & Searchmatrixsortingstrings

Last updated

Build a string for each anti-diagonal of a letter grid, read bottom-left to top-right, and return diagonal indices ordered by string, with ties broken by index.

You are given a grid of lowercase letters with m rows and n columns. Cells whose row and column indices add up to the same number lie on the same anti-diagonal. For a cell at row r and column c, the anti-diagonal number is d = r + c, so the grid has exactly m + n - 1 anti-diagonals, numbered 0 through m + n - 2.

For every anti-diagonal d, form a word by reading its letters starting at the cell with the largest row index and moving up and to the right, ending at the cell with the smallest row index. Join the letters in that order into one string.

Return all diagonal numbers, arranged so that their words are in ascending dictionary (lexicographic) order. A word that is a proper prefix of another comes before it. If two diagonals produce identical words, the one with the smaller number comes first.

Task

Implement rank_diagonals(grid), which takes the grid as a list of rows (each a list of single-character strings) and returns a list of integers: the diagonal numbers in the required order.

Constraints

  • m == len(grid) and n == len(grid[0])
  • 1 <= m, n <= 500
  • 1 <= m * n <= 10^5
  • Every entry of grid is a single lowercase English letter ('a' to 'z').
  • All rows have the same length.

Examples

Example 1

Input: rank_diagonals([['b', 'a'], ['a', 'b']])

Output: [1, 0, 2]

Example 2

Input: rank_diagonals([['c', 'a', 't'], ['d', 'o', 'g'], ['e', 'l', 'm']])

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

Hints

Hint 1

Every cell on one anti-diagonal shares the same value of r + c, so diagonal d contains the cells (r, d - r) that fall inside the grid.

Hint 2

For diagonal d, the valid rows run from max(0, d - (n - 1)) up to min(m - 1, d). Iterate from the larger row down to the smaller one to get the required reading order.

Hint 3

Sort pairs of (word, d). Tuple comparison orders by the word first and then by d, which gives exactly the required tie-break.