#2711
Medium Algorithms Difference of number of distinct values on diagonals
Array Hash Table Matrix
68.4% acceptance
Feb 25, 2026
143
211
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 cell grid[r][c] not including the cell grid[r][c] itself.
Let 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.
Then answer[r][c] = |leftAbove[r][c] - rightBelow[r][c]|.
Solution
Rust
Time O(n * m)
Space O(n * m)
impl Solution {
pub fn difference_of_distinct_values(grid: Vec<Vec<i32>>) -> Vec<Vec<i32>> {
let m = grid.len();
let n = grid[0].len();
let mut ans = vec![vec![0i32; n]; m];
for r in 0..m {
for c in 0..n {
let mut set: std::collections::HashSet<i32> = std::collections::HashSet::new();
let (mut i, mut j) = (r as i32 - 1, c as i32 - 1);
while i >= 0 && j >= 0 {
set.insert(grid[i as usize][j as usize]);
i -= 1; j -= 1;
}
let la = set.len() as i32;
set.clear();
let (mut i, mut j) = (r + 1, c + 1);
while i < m && j < n {
set.insert(grid[i][j]);
i += 1; j += 1;
}
let rb = set.len() as i32;
ans[r][c] = (la - rb).abs();
}
}
ans
}
}