#2711
Difference of Number of Distinct Values on Diagonals
MediumArrayHash TableMatrixHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
In the optimal approach, we will traverse the grid only once and maintain two arrays to track the distinct counts of leftAbove and rightBelow values dynamically. This avoids redundant calculations and significantly improves efficiency.
⚙️
Algorithm
4 steps- 1Step 1: Create two arrays to store the distinct counts for leftAbove and rightBelow diagonals.
- 2Step 2: Traverse the grid to fill the leftAbove counts in one pass.
- 3Step 3: Traverse the grid in reverse to fill the rightBelow counts.
- 4Step 4: Calculate the answer matrix using the counts from both arrays.
solution.py30 lines
1# Full working Python code
2
3def differenceOfDistinctValues(grid):
4 m, n = len(grid), len(grid[0])
5 leftAbove = [{} for _ in range(m + n - 1)]
6 rightBelow = [{} for _ in range(m + n - 1)]
7 answer = [[0] * n for _ in range(m)]
8
9 # Fill leftAbove counts
10 for r in range(m):
11 for c in range(n):
12 diag = r - c + (n - 1)
13 leftAbove[diag][grid[r][c]] = leftAbove[diag].get(grid[r][c], 0) + 1
14
15 # Fill rightBelow counts
16 for r in range(m - 1, -1, -1):
17 for c in range(n - 1, -1, -1):
18 diag = r - c + (n - 1)
19 rightBelow[diag][grid[r][c]] = rightBelow[diag].get(grid[r][c], 0) + 1
20
21 # Calculate answer
22 for r in range(m):
23 for c in range(n):
24 diag = r - c + (n - 1)
25 leftCount = len(leftAbove[diag]) - (1 if grid[r][c] in leftAbove[diag] else 0)
26 rightCount = len(rightBelow[diag]) - (1 if grid[r][c] in rightBelow[diag] else 0)
27 answer[r][c] = abs(leftCount - rightCount)
28
29 return answer
30ℹ
Complexity note: This complexity arises because we traverse the grid a constant number of times (twice) and use additional space for storing counts of distinct elements, which is proportional to the number of diagonals.
- 1Understanding diagonal traversal is key to solving this problem.
- 2Using hash maps can help efficiently count distinct elements.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.