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: [9, 9]
💡 Note: For value 4 at position (1,1): adjacent neighbors are 1+2+1+5=9, diagonal neighbors are 3+2+5+4=14. But there are two 4's, so we get the first occurrence.
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
Design Neighbor Sum Service: Grid → Position Map → Fast Queries312144554Input GridPosition Map3→(0,0) 1→(0,1)4→(1,1)5→(2,0) 5→(2,1)Preprocess O(n²)adjacentSum(4)Lookup: O(1)Sum: 1+2+1+5=9Query O(1)Total: O(n²) preprocessing + O(1) per querySpace: O(n²) for position mapping
Understanding the Visualization
1
Input Grid
3×3 grid with distinct values [0, n²-1]
2
Preprocess
Map each value to its (row, col) position
3
Query Operations
Fast neighbor sum calculation using position lookup
Key Takeaway
🎯 Key Insight: Pre-compute value→position mapping once for O(1) position lookup during neighbor sum queries
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