|
| 1 | +2711\. Difference of Number of Distinct Values on Diagonals |
| 2 | + |
| 3 | +Medium |
| 4 | + |
| 5 | +Given a **0-indexed** 2D `grid` of size `m x n`, you should find the matrix `answer` of size `m x n`. |
| 6 | + |
| 7 | +The value of each cell `(r, c)` of the matrix `answer` is calculated in the following way: |
| 8 | + |
| 9 | +* Let `topLeft[r][c]` be the number of **distinct** values in the top-left diagonal of the cell `(r, c)` in the matrix `grid`. |
| 10 | +* Let `bottomRight[r][c]` be the number of **distinct** values in the bottom-right diagonal of the cell `(r, c)` in the matrix `grid`. |
| 11 | + |
| 12 | +Then `answer[r][c] = |topLeft[r][c] - bottomRight[r][c]|`. |
| 13 | + |
| 14 | +Return _the matrix_ `answer`. |
| 15 | + |
| 16 | +A **matrix diagonal** is a diagonal line of cells starting from some cell in either the topmost row or leftmost column and going in the bottom-right direction until reaching the matrix's end. |
| 17 | + |
| 18 | +A cell <code>(r<sub>1</sub>, c<sub>1</sub>)</code> belongs to the top-left diagonal of the cell `(r, c)`, if both belong to the same diagonal and <code>r<sub>1</sub> < r</code>. Similarly is defined bottom-right diagonal. |
| 19 | + |
| 20 | +**Example 1:** |
| 21 | + |
| 22 | + |
| 23 | + |
| 24 | +**Input:** grid = [[1,2,3],[3,1,5],[3,2,1]] |
| 25 | + |
| 26 | +**Output:** [[1,1,0],[1,0,1],[0,1,1]] |
| 27 | + |
| 28 | +**Explanation:** |
| 29 | + |
| 30 | +The 1<sup>st</sup> diagram denotes the initial grid. |
| 31 | + |
| 32 | +The 2<sup>nd</sup> diagram denotes a grid for cell (0,0), where blue-colored cells are cells on its bottom-right diagonal. |
| 33 | + |
| 34 | +The 3<sup>rd</sup> diagram denotes a grid for cell (1,2), where red-colored cells are cells on its top-left diagonal. |
| 35 | + |
| 36 | +The 4<sup>th</sup> diagram denotes a grid for cell (1,1), where blue-colored cells are cells on its bottom-right diagonal and red-colored cells are cells on its top-left diagonal. |
| 37 | +- The cell (0,0) contains [1,1] on its bottom-right diagonal and [] on its top-left diagonal. The answer is |1 - 0| = 1. |
| 38 | +- The cell (1,2) contains [] on its bottom-right diagonal and [2] on its top-left diagonal. The answer is |0 - 1| = 1. |
| 39 | +- The cell (1,1) contains [1] on its bottom-right diagonal and [1] on its top-left diagonal. The answer is |1 - 1| = 0. |
| 40 | + |
| 41 | +The answers of other cells are similarly calculated. |
| 42 | + |
| 43 | +**Example 2:** |
| 44 | + |
| 45 | +**Input:** grid = [[1]] |
| 46 | + |
| 47 | +**Output:** [[0]] |
| 48 | + |
| 49 | +**Explanation:** - The cell (0,0) contains [] on its bottom-right diagonal and [] on its top-left diagonal. The answer is |0 - 0| = 0. |
| 50 | + |
| 51 | +**Constraints:** |
| 52 | + |
| 53 | +* `m == grid.length` |
| 54 | +* `n == grid[i].length` |
| 55 | +* `1 <= m, n, grid[i][j] <= 50` |
0 commit comments