Difference of Number of Distinct Values on Diagonals - Problem
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.
Return the matrix answer.
Input & Output
Example 1 — Basic 3x3 Grid
$
Input:
grid = [[1,2,3],[4,5,6],[7,8,9]]
›
Output:
[[2,1,0],[1,0,1],[0,1,2]]
💡 Note:
For cell (1,1) with value 5: left/above has {1} (1 distinct), right/below has {9} (1 distinct), so |1-1|=0. For cell (0,0): no left/above (0 distinct), right/below has {5,9} (2 distinct), so |0-2|=2.
Example 2 — Small 2x2 Grid
$
Input:
grid = [[1,2],[3,4]]
›
Output:
[[1,0],[0,1]]
💡 Note:
Cell (0,0): no left/above, right/below has {4}, difference=1. Cell (1,1): left/above has {1}, no right/below, difference=1.
Example 3 — Duplicate Values
$
Input:
grid = [[1,1,1],[1,1,1],[1,1,1]]
›
Output:
[[0,0,0],[0,0,0],[0,0,0]]
💡 Note:
All values are the same, so each diagonal has at most 1 distinct value. Every cell will have equal counts on both sides, resulting in difference 0.
Constraints
- 1 ≤ m, n ≤ 50
- 1 ≤ grid[i][j] ≤ 50
Visualization
Tap to expand
Understanding the Visualization
1
Input Matrix
3x3 grid with values 1-9
2
Diagonal Analysis
Count distinct values left/above vs right/below each cell
3
Result Matrix
Absolute differences for each position
Key Takeaway
🎯 Key Insight: Each diagonal can be processed independently to count distinct values efficiently
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code