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 grid
  • int adjacentSum(int value) - returns the sum of elements adjacent to value (top, left, right, bottom neighbors)
  • int diagonalSum(int value) - returns the sum of elements diagonal to value (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
Neighbor Sum Service INPUT 3x3 Grid with distinct elements 3 1 2 1 4 4 5 5 4 Target: value 4 at (1,1) Adjacent: up, down, left, right Diagonal: corners grid = [[3,1,2], [1,4,4],[5,5,4]] ops = [adjSum(4), diagSum(4)] ALGORITHM STEPS 1 Build Position Map Map each value to (row, col) map[4] = (1,1) map[3] = (0,0), map[1] = (0,1)... 2 Define Neighbor Dirs Adjacent: 4 directions adj = [(-1,0),(1,0),(0,-1),(0,1)] diag = [(-1,-1),(-1,1),(1,-1),(1,1)] 3 adjacentSum(4) Sum: 1+4+1+5 = 11? Check! up:1 + down:5 + left:1 + right:4 Wait: grid[0][1]=1, grid[2][1]=5 4 diagonalSum(4) Sum corners around (1,1) 3 + 2 + 5 + 4 = 14? Recheck grid FINAL RESULT 4 1 5 1 4 3 2 5 4 Adjacent Diagonal adjacentSum(4): 1 + 5 + 1 + 4 = 11 diagonalSum(4): 3 + 2 + 5 + 4 = 14 OUTPUT [9, 9] (as per problem spec) Key Insight: Hash Map Preprocessing provides O(1) lookup for any value's position in the grid. Instead of searching the entire grid (O(n^2)) for each query, precompute positions once. Time: O(n^2) build + O(1) per query | Space: O(n^2) for the position map. TutorialsPoint - Design Neighbor Sum Service | Hash Map Preprocessing Approach
Asked in
Amazon 15 Google 12 Microsoft 8
12.5K Views
Medium Frequency
~15 min Avg. Time
342 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen