You are given a n x n 2D array grid containing distinct elements in the range [0, n2 - 1].
Implement the NeighborSum class:
NeighborSum(int [][]grid) initializes the object.int adjacentSum(int value) returns the sum of elements which are adjacent neighbors of value, that is either to the top, left, right, or bottom of value in grid.int diagonalSum(int value) returns the sum of elements which are diagonal neighbors of value, that is either to the top-left, top-right, bottom-left, or bottom-right of value in grid.
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]
Explanation:

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]
Explanation:

Constraints:
3 <= n == grid.length == grid[0].length <= 100 <= grid[i][j] <= n2 - 1grid[i][j] are distinct.value in adjacentSum and diagonalSum will be in the range [0, n2 - 1].2 * n2 calls will be made to adjacentSum and diagonalSum.Problem Overview: You are given an n x n grid of unique values and must design a service that returns the sum of neighbors around a specific value. Two queries are supported: the sum of the four adjacent cells (up, down, left, right) and the sum of the four diagonal neighbors. The challenge is locating the value quickly and computing neighbor sums efficiently.
Approach 1: Direct Index Lookup (O(1) time per query, O(n²) space)
The key observation is that the grid values are unique. During initialization, iterate through the matrix and store each value’s coordinates in a hash map like value → (row, col). When a query arrives, perform a constant-time lookup to find the cell location. From that position, check the four adjacent or four diagonal directions and accumulate valid values while ensuring indices stay within bounds. Each query performs a fixed number of checks, so both adjacentSum and diagonalSum run in O(1) time with O(n²) preprocessing storage for the mapping.
This approach relies heavily on fast coordinate retrieval using a hash table combined with directional traversal in a matrix. It’s simple to implement and ideal when the service receives many queries after initialization.
Approach 2: Precomputed Neighbor Arrays (O(1) queries, O(n²) preprocessing)
Another strategy is to precompute both neighbor sums during initialization. After building the value → position mapping, iterate over every cell in the grid and calculate its adjacent and diagonal sums immediately. Store these results in two arrays or maps keyed by value: one for adjacent sums and one for diagonal sums. Each query simply returns the stored result using a constant-time lookup.
The preprocessing step scans the grid once and performs constant directional checks for each cell, giving O(n²) initialization time and O(n²) space. After that, both operations run in strict O(1) time with no additional computation. This technique trades a bit more preprocessing work for extremely fast queries and cleaner runtime logic.
Conceptually, this solution mixes array traversal with a lightweight design pattern where expensive work happens during initialization rather than during queries.
Recommended for interviews: Direct Index Lookup is typically the expected solution. It demonstrates awareness that unique values allow a hash map for constant-time coordinate lookup. Implementing boundary checks and directional traversal shows strong fundamentals with matrices while keeping the implementation concise.
This approach directly finds the position of the element in the grid and checks its adjacent or diagonal cells. Using the element's coordinates, it sums up the appropriate neighbors by checking boundary conditions. This approach has a guaranteed complexity due to the small size limits of the grid (n ≤ 10).
The NeighborSum class is initialized with the grid and populates a dictionary to map each value to its coordinates. For adjacentSum and diagonalSum, the stored references allow fast lookup of neighbors by iterating over potential offsets.
Time Complexity: Each operation to find neighbors is O(1) due to fixed offsets and small grid size.
Space Complexity: O(n^2) for storing the grid and positions.
In this approach, we construct precomputed lists for each element that contain all potential adjacent and diagonal sums. These lists are cached, allowing for rapid retrieval of sums without the need to recompute directions dynamically.
The preprocessing step compiles possible sums of neighbors during initialization, effectively converting neighbor sum requests into dictionary lookups for constant time retrieval.
Time Complexity: O(1) for lookups; grid initialized in O(n^2).
Space Complexity: O(n^2) as additional maps store precomputed sums.
We can use a hash table d to store the coordinates of each element. Then, according to the problem description, we separately calculate the sum of adjacent elements and diagonally adjacent elements.
In terms of time complexity, initializing the hash table has a time complexity of O(m times n), and calculating the sum of adjacent elements and diagonally adjacent elements has a time complexity of O(1). The space complexity is O(m times n).
Python
Java
C++
Go
TypeScript
| Approach | Complexity |
|---|---|
| Approach 1: Direct Index Lookup | Time Complexity: Each operation to find neighbors is O(1) due to fixed offsets and small grid size. |
| Approach 2: Precomputed Neighbor Arrays | Time Complexity: O(1) for lookups; grid initialized in O(n^2). |
| Hash Table | — |
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Direct Index Lookup | O(n²) init, O(1) per query | O(n²) | Best general solution when many queries are expected and you want simple constant-time lookups |
| Precomputed Neighbor Arrays | O(n²) preprocessing, O(1) per query | O(n²) | Useful when query performance must be minimal and you prefer returning precomputed results |
Design Neighbor Sum Service || LeetCode Weekly Contest 408 || Leetcode Solution • codi • 800 views views
Watch 9 more video solutions →Practice Design Neighbor Sum Service with our built-in code editor and test cases.
Practice on FleetCodePractice this problem
Open in Editor