LeetCode solutions

3516. Design Neighbor Sum Service

My accepted Python solution to LeetCode problem 3516, Design Neighbor Sum Service, running in 28ms.

  • Difficulty: Easy
  • Python
  • Runtime 28ms
  • Memory 17.6MB

Read the problem on LeetCode View on GitHub

Python

Accepted on LeetCode — runtime 28ms, memory 17.6MB, accepted 2025-12-31.

python
class NeighborSum:

    def __init__(self, grid: List[List[int]]):
        self.grid = grid
        self.n = len(grid)
        # Store position of each value
        self.pos = {}
        for i in range(self.n):
            for j in range(self.n):
                self.pos[grid[i][j]] = (i, j)

    def adjacentSum(self, value: int) -> int:
        i, j = self.pos[value]
        total = 0
        # up, down, left, right
        for di, dj in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
            ni, nj = i + di, j + dj
            if 0 <= ni < self.n and 0 <= nj < self.n:
                total += self.grid[ni][nj]
        return total

    def diagonalSum(self, value: int) -> int:
        i, j = self.pos[value]
        total = 0
        # top-left, top-right, bottom-left, bottom-right
        for di, dj in [(-1, -1), (-1, 1), (1, -1), (1, 1)]:
            ni, nj = i + di, j + dj
            if 0 <= ni < self.n and 0 <= nj < self.n:
                total += self.grid[ni][nj]
        return total

Source