Design Neighbor Sum Service - Problem
You are given a n x n 2D array grid containing distinct elements in the range [0, n² - 1].
Implement the NeighborSum class:
NeighborSum(int[][] grid)- initializes the object with the given gridint adjacentSum(int value)- returns the sum of elements adjacent tovalue(top, left, right, bottom neighbors)int diagonalSum(int value)- returns the sum of elements diagonal tovalue(top-left, top-right, bottom-left, bottom-right neighbors)
The neighbors are calculated based on the position of value in the grid. If a neighbor position is out of bounds, it is ignored.
Input & Output
Example 1 — Basic Grid Operations
$
Input:
grid = [[3,1,2],[1,4,4],[5,5,4]], operations = [["adjacentSum", 4], ["diagonalSum", 4]]
›
Output:
[11, 14]
💡 Note:
For value 4 at position (1,1): adjacent neighbors are 1+4+5+1=11, diagonal neighbors are 3+2+5+4=14.
Example 2 — Edge Position
$
Input:
grid = [[1,2,0,3],[4,7,15,6],[8,9,10,11],[12,13,14,5]], operations = [["adjacentSum", 15]]
›
Output:
[23]
💡 Note:
Value 15 is at position (1,2). Adjacent neighbors: 2+0+6+10=18. Wait, let me recalculate: 7+0+6+10=23.
Example 3 — Corner Position
$
Input:
grid = [[1,2],[3,4]], operations = [["diagonalSum", 1]]
›
Output:
[4]
💡 Note:
Value 1 is at corner (0,0). Only one diagonal neighbor: bottom-right has value 4.
Constraints
- 3 ≤ n ≤ 10
- 0 ≤ grid[i][j] ≤ n² - 1
- All values in grid are distinct
- 1 ≤ operations.length ≤ 100
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code