Ad platform~20 min2s · 256 MBtarget O(m * n) time, O(1) spaceclassic twin: lc-498traversal
An ad team keeps a grid of scores. Each row is a placement on the page and each place in a row is an hour of the day. A cell is the score of one ad in that placement and hour.
A report prints the scores along the diagonals that run from the lower left to the upper right. It starts at the top left cell, and the first diagonal is that one cell.
The report goes up the first diagonal, then down the second, then up the third, and so on. A grid can be wide, tall, or a single row or column.
Write diagonal_order(scores).
scores[r][c] is the score in row r and place c. All rows have the same length.d holds the cells with r + c = d. Diagonal 0 is the top left cell.Input: scores = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Output: [1, 2, 4, 7, 5, 3, 6, 8, 9]The grid has 3 rows and 3 places, so there are 5 diagonals.
| Diagonal d | Direction | Scores read |
|---|---|---|
| 0 | up | 1 |
| 1 | down | 2, 4 |
| 2 | up | 7, 5, 3 |
| 3 | down | 6, 8 |
| 4 | up | 9 |
Input: scores = [[1, 2, 3, 4], [5, 6, 7, 8]]
Output: [1, 2, 5, 6, 3, 4, 7, 8]A wide grid has more diagonals than rows. The last diagonals start in the last row.
Input: scores = [[1, 2], [3, 4], [5, 6]]
Output: [1, 2, 3, 5, 4, 6]A tall grid ends on its last row, and the last diagonal is one cell.
1 ≤ scores.length ≤ 500 (rows)1 ≤ scores[r].length ≤ 500 (places in a row, the same for every row)1 ≤ scores[r][c] ≤ 1,000,000 (score of one ad)There are 250,000 cells and 999 diagonals. Scanning the whole grid for each diagonal reads 249,750,000 cells.
Every cell sits on exactly one diagonal and its place follows from d - row, so 250,000 reads are enough.