Difference of Number of Distinct Values on Diagonals Problem
#2711
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 2711.
Given a 2D grid of size m x n, you should find the matrix answer of size m x n.
The cell answer[r][c] is calculated by looking at the diagonal values of the cell grid[r][c]:
- Let
leftAbove[r][c]be the number of distinct values on the diagonal to the left and above the cellgrid[r][c]not including the cellgrid[r][c]itself. - Let
rightBelow[r][c]be the number of distinct values on the diagonal to the right and below the cellgrid[r][c], not including the cellgrid[r][c]itself. - Then
answer[r][c] = |leftAbove[r][c] - rightBelow[r][c]|.
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 the end of the matrix is reached.
- For example, in the below diagram the diagonal is highlighted using the cell with indices
(2, 3)colored gray:- Red-colored cells are left and above the cell.
- Blue-colored cells are right and below the cell.

Return the matrix answer.
Example 1:
Input: grid = [[1,2,3],[3,1,5],[3,2,1]]
Output: [[1,1,0],[1,0,1],[0,1,1]]
Explanation:
To calculate the answer cells:
answer left-above elements leftAbove right-below elements rightBelow |leftAbove - rightBelow|
[0][0] [] 0 [grid[1][1], grid[2][2]] |{1, 1}| = 1 1
[0][1] [] 0 [grid[1][2]] |{5}| = 1 1
[0][2] [] 0 [] 0 0
[1][0] [] 0 [grid[2][1]] |{2}| = 1 1
[1][1] [grid[0][0]] |{1}| = 1 [grid[2][2]] |{1}| = 1 0
[1][2] [grid[0][1]] |{2}| = 1 [] 0 1
[2][0] [] 0 [] 0 0
[2][1] [grid[1][0]] |{3}| = 1 [] 0 1
[2][2] [grid[0][0], grid[1][1]] |{1, 1}| = 1 [] 0 1
Example 2:
Input: grid = [[1]]
Output: [[0]]
Constraints:
m == grid.lengthn == grid[i].length1 <= m, n, grid[i][j] <= 50
Solution
Approach: Simulation
For every cell, walk up-left along its diagonal collecting values in a set to get tl, then walk down-right in the same way to get br. The answer for the cell is |tl - br|.
Complexity: O(m * n * min(m, n)) time and O(min(m, n)) extra space for the set (O(m * n) for the result).
class Solution:
def differenceOfDistinctValues(self, grid: List[List[int]]) -> List[List[int]]:
m, n = len(grid), len(grid[0])
ans = [[0] * n for _ in range(m)]
for i in range(m):
for j in range(n):
x, y = i, j
s = set()
while x and y:
x, y = x - 1, y - 1
s.add(grid[x][y])
tl = len(s)
x, y = i, j
s = set()
while x + 1 < m and y + 1 < n:
x, y = x + 1, y + 1
s.add(grid[x][y])
br = len(s)
ans[i][j] = abs(tl - br)
return ans