Difference of Number of Distinct Values on Diagonals — LeetCode 2711 Python Solution
- Problem
- #2711
- Pattern
- Matrix and Grid
- Reading time
- 4 min
- Source
- leetcode.com
The 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 cell grid[r][c] not including the cell grid[r][c] itself.
Python solution
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 ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(m \times n \times \min(m, n)) |
| Space | O(m \times n) auxiliary |
Pattern: Matrix and Grid
Treat a 2-D grid as a graph whose neighbours are the four adjacent cells. LeetCode 2711. Difference of Number of Distinct Values on Diagonals is filed here because LeetCode tags it Matrix, which is the vocabulary this hub collects.
The matrix and grid guide has the Python template for the pattern and the 216 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2711. Difference of Number of Distinct Values on Diagonals?
- LeetCode 2711. Difference of Number of Distinct Values on Diagonals is rated Medium on LeetCode.
- What is the time complexity of LeetCode 2711. Difference of Number of Distinct Values on Diagonals?
- The Python solution on this page runs in O(m \times n \times \min(m, n)).
- What is the space complexity of LeetCode 2711. Difference of Number of Distinct Values on Diagonals?
- The Python solution on this page uses O(m \times n) auxiliary space.
- What topics does LeetCode 2711. Difference of Number of Distinct Values on Diagonals cover?
- LeetCode 2711. Difference of Number of Distinct Values on Diagonals is tagged Array, Hash Table and Matrix on LeetCode.