Problem Description
Given an m x n grid, for each cell compute two values:
- leftAbove[r][c]: the number of distinct elements on the top-left diagonal from (r, c), excluding grid[r][c].
- rightBelow[r][c]: the number of distinct elements on the bottom-right diagonal from (r, c), excluding grid[r][c]. Then, answer[r][c] = |leftAbove[r][c] − rightBelow[r][c]|. Return the answer matrix.
Key Insights
- All cells that lie on the same diagonal share the same r - c constant. This lets us process diagonals independently.
- For each diagonal, compute prefix distinct counts (for left-above values) and suffix distinct counts (for right-below values).
- Using precomputation per diagonal avoids recomputing sets repeatedly for every cell.
Space and Time Complexity
Time Complexity: O(mn) – each cell is processed as part of its diagonal. Space Complexity: O(mn) – additional space is used for storing distinct counts for each diagonal.
Solution
The approach is to group cells by their diagonal using the key (r - c). For each diagonal, we get cells in order from top-left to bottom-right. We then build two arrays:
- Prefix array: For each cell at index i on the diagonal, store the count of distinct values from the start until i-1.
- Suffix array: For each cell at index i, store the count of distinct values from i+1 until the end. Finally, for each cell we compute the absolute difference between its prefix and suffix distinct counts and assign that value to answer[r][c]. This method efficiently calculates the required value using set and dictionary operations to track distinct elements.