#3242
Design Neighbor Sum Service
EasyArrayHash TableDesignMatrixSimulationHash 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)
By storing the positions of each value in a hash map, we can quickly access the coordinates of any value, allowing us to compute sums in constant time.
⚙️
Algorithm
3 steps- 1Step 1: Create a hash map to store the coordinates of each value in the grid during initialization.
- 2Step 2: For adjacentSum, retrieve the coordinates of the value and sum the values of its four adjacent neighbors using the hash map.
- 3Step 3: For diagonalSum, retrieve the coordinates and sum the values of its four diagonal neighbors using the hash map.
solution.py23 lines
1class NeighborSum:
2 def __init__(self, grid):
3 self.grid = grid
4 self.n = len(grid)
5 self.position_map = {grid[i][j]: (i, j) for i in range(self.n) for j in range(self.n)}
6
7 def adjacentSum(self, value):
8 i, j = self.position_map[value]
9 sum_adj = 0
10 if i > 0: sum_adj += self.grid[i-1][j] # up
11 if i < self.n - 1: sum_adj += self.grid[i+1][j] # down
12 if j > 0: sum_adj += self.grid[i][j-1] # left
13 if j < self.n - 1: sum_adj += self.grid[i][j+1] # right
14 return sum_adj
15
16 def diagonalSum(self, value):
17 i, j = self.position_map[value]
18 sum_diag = 0
19 if i > 0 and j > 0: sum_diag += self.grid[i-1][j-1] # top-left
20 if i > 0 and j < self.n - 1: sum_diag += self.grid[i-1][j+1] # top-right
21 if i < self.n - 1 and j > 0: sum_diag += self.grid[i+1][j-1] # bottom-left
22 if i < self.n - 1 and j < self.n - 1: sum_diag += self.grid[i+1][j+1] # bottom-right
23 return sum_diagℹ
Complexity note: The time complexity is O(n) for the lookup of coordinates, as we use a hash map. The space complexity is O(n) due to storing the positions of each element.
- 1Using a hash map for coordinate storage allows for O(1) access time for neighbor lookups.
- 2Understanding the difference between adjacent and diagonal neighbors is crucial for implementing the sums correctly.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.