Rank Anti-Diagonal Strings of a Letter Grid
Heaps, Sorting & SearchAuto-graded · 17 test casesLast 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)andn == len(grid[0])1 <= m, n <= 5001 <= m * n <= 10^5- Every entry of
gridis 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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
All cells on anti-diagonal d satisfy r + c = d, so the diagonal consists of the cells (r, d - r) that lie inside the grid. That requires 0 <= r < m and 0 <= d - r < n, giving the row range:
low = max(0, d - (n - 1))high = min(m - 1, d)
Walking r from high down to low visits the diagonal from its bottom-left end to its top-right end, which is the required reading order. Join the letters to get the word for d.
Then build pairs (word, d) and sort them. Python compares tuples element by element: first by the word lexicographically (with a proper prefix sorting before a longer string), and when words are equal, by d ascending. This matches the required ordering exactly. Finally, output the d values in sorted order.
Why it is correct
- Each cell belongs to exactly one diagonal
r + c, and the row bounds come directly from the grid limits, so every cell is read exactly once and no outside cell is read. - Decreasing
rwhilec = d - rincreases is exactly "up and to the right", starting from the bottom-left-most cell. - Since
dis unique per pair, the sort key is a total order, so the result is deterministic and the tie-break rule is satisfied.
Complexity
Let L = min(m, n) be the longest diagonal length.
- Time: building all words is
O(m * n). Sortingm + n - 1pairs costsO((m + n) log(m + n))comparisons, each taking up toO(L)time, so the worst case isO((m + n) log(m + n) * L). Withm * n <= 10^5this is small. - Space:
O(m * n)for the stored words plusO(m + n)for the pairs and output.
Reference solution
def rank_diagonals(grid):
m = len(grid)
n = len(grid[0])
words = []
for d in range(m + n - 1):
low = max(0, d - (n - 1))
high = min(m - 1, d)
letters = []
for r in range(high, low - 1, -1):
letters.append(grid[r][d - r])
words.append(("".join(letters), d))
words.sort()
return [d for _, d in words]