Skip to content

Practice Design Neighbor Sum Service

Read the task, work through the examples, and check your approach against the constraints. Use the original LeetCode task for coding and submissions.

Easy#3242
LeetCode Problem

Design Neighbor Sum Service

Problem Statement

Implement NeighborSum for an n by n grid containing each integer from 0 through n^2 - 1 exactly once. NeighborSum(grid) stores the grid. adjacentSum(value) returns the sum of the existing cells immediately above, below, left, and right of value. diagonalSum(value) returns the sum of its existing four diagonal neighbors. Cells outside the grid contribute nothing.

Source: Design Neighbor Sum Service on LeetCode. Use the original task for its coding environment and submissions.

Examples

# Example 1

Input
["NeighborSum", "adjacentSum", "adjacentSum", "diagonalSum", "diagonalSum"] [[[[0, 1, 2], [3, 4, 5], [6, 7, 8]]], [1], [4], [4], [8]]
Output
[null, 6, 16, 16, 4]

# Example 2

Input
["NeighborSum", "adjacentSum", "diagonalSum"] [[[[1, 2, 0, 3], [4, 7, 15, 6], [8, 9, 10, 11], [12, 13, 14, 5]]], [15], [9]]
Output
[null, 23, 45]

Constraints

3 <= n == grid.length == grid[0].length <= 10
0 <= grid[i][j] <= n^2 - 1
All grid[i][j] are distinct.
value in adjacentSum and diagonalSum will be in the range [0, n^2 - 1].
At most 2 * n^2 calls will be made to adjacentSum and diagonalSum.

Related LeetCode Problems

Practice more problems similar to Design Neighbor Sum Service.

Review your practice with PhantomCodeAI

After trying the problem yourself, use the app to discuss your approach, complexity, and edge cases.