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]:
leftAbove[r][c] be the number of distinct values on the diagonal to the left and above the cell grid[r][c] not including the cell grid[r][c] itself.rightBelow[r][c] be the number of distinct values on the diagonal to the right and below the cell grid[r][c], not including the cell grid[r][c] itself.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.
(2, 3) colored gray:

Return the matrix answer.
Example 1:
Input: grid = [[1,2,3],[3,1,5],[3,2,1]]
Output: 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: Output: [[0]]
Constraints:
m == grid.lengthn == grid[i].length1 <= m, n, grid[i][j] <= 50Problem Overview: You are given an m x n grid. For every cell (i, j), compute the absolute difference between the number of distinct values on the top-left diagonal before that cell and the number of distinct values on the bottom-right diagonal after it. The result is stored in a matrix of the same size.
Approach 1: Diagonal Traversal with Precomputation (O(m*n) time, O(m*n) space)
Each cell belongs to exactly one top-left → bottom-right diagonal. Traverse every diagonal and compute two pieces of information: the count of distinct values seen before each position and the count of distinct values after it. Use a hash set while walking the diagonal from top-left to bottom-right to track distinct values encountered so far, storing prefix counts. Then walk the same diagonal in reverse to collect suffix distinct counts. The result for each cell is abs(prefixDistinct - suffixDistinct). This approach processes each element a constant number of times, giving O(m*n) time. Extra arrays for prefix/suffix information lead to O(m*n) space.
Diagonal traversal is a common pattern in matrix problems where elements share structural relationships. Using a hash table or set ensures distinct checks remain O(1) on average.
Approach 2: Simultaneous Diagonal Pass Method (O(m*n) time, O(min(m,n)) space)
Instead of storing prefix and suffix arrays, process each diagonal in a single controlled pass using two hash sets. Move along the diagonal and maintain a set of values already seen (top-left side). Before updating it, compute the number of distinct values remaining on the bottom-right side by maintaining another set or pre-counted structure. As you advance, shift elements from the future set to the past set and update the answer in place. Because each diagonal length is at most min(m, n), the auxiliary memory remains bounded by the diagonal size rather than the whole matrix.
This method keeps the same O(m*n) runtime but reduces auxiliary memory usage. It relies heavily on fast set operations and careful ordering of updates while iterating along the diagonal.
Problems like this combine array traversal with diagonal indexing tricks. The key insight: treat each diagonal independently instead of recalculating distinct counts from every cell.
Recommended for interviews: The diagonal traversal with precomputation approach is the safest explanation during interviews. It clearly demonstrates how you decompose the matrix into diagonals and track distinct values using hash sets. Once the interviewer sees the O(m*n) logic, mentioning the simultaneous-pass optimization shows deeper understanding of space tradeoffs.
This approach involves precomputing diagonal elements so that when we calculate distinct values for each diagonal, we can directly access those precomputed results instead of recalculating them from scratch for every cell.
The C implementation uses a naive diagonal traversal method, maintaining sets of diagonals and calculating distinct values of these diagonals in advance. This allows us to access distinct counts efficiently.
Time Complexity: O(m * n), where m and n are dimensions of the grid.
Space Complexity: O(m * n), for storing leftAbove and rightBelow counts.
This strategy employs a simultaneous diagonal pass from both directions using a two-pointer strategy to dynamically compute and update diagonal distinct values while traversing the grid matrix.
Utilizing two directions with usage of an array to calculate and maintain the current distinct element count, the C solution uses manual memory management to balance complexity.
Time Complexity: O(m * n) - Each diagonal value is set once per element.
Space Complexity: O(max(m, n)) - Due to diagonal operational arrays.
We can simulate the process described in the problem statement, calculating the number of distinct values on the top-left diagonal tl and the bottom-right diagonal br for each cell, then compute their difference |tl - br|.
The time complexity is O(m times n times min(m, n)), and the space complexity is O(m times n).
Python
Java
C++
Go
TypeScript
| Approach | Complexity |
|---|---|
| Diagonal Traversal with Precomputation | Time Complexity: O(m * n), where m and n are dimensions of the grid. |
| Simultaneous Diagonal Pass Method | Time Complexity: O(m * n) - Each diagonal value is set once per element. |
| Simulation | — |
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Diagonal Traversal with Precomputation | O(m*n) | O(m*n) | Best for clarity and interviews; easy to reason about prefix and suffix distinct counts per diagonal |
| Simultaneous Diagonal Pass Method | O(m*n) | O(min(m,n)) | When memory usage matters and you want to avoid storing extra matrices |
6440. Difference of Number of Distinct Values on Diagonals | Leetcode Weekly Contest 347| Solution. • Optimization • 868 views views
Watch 5 more video solutions →Practice Difference of Number of Distinct Values on Diagonals with our built-in code editor and test cases.
Practice on FleetCodePractice this problem
Open in Editor