← Back to index
MediumTypeScript3 min read

Design Neighbor Sum Service

design a service to compute sums of adjacent and diagonal neighbors using prefix sums and linear search.

designmatrixprefix-sum

Problem link

View on LeetCode

Solutions in this repo

  • TypeScript../design-neighbor-sum-service/solution.tsTypeScript solution

build a prefix sum during construction for efficient range queries (though not strictly needed here). for neighbor sums, find the target value's position, then sum its four adjacent or four diagonal neighbors with bounds checking.

the key is safe access: check bounds before accessing grid cells to handle edge cases where neighbors might be out of bounds.

methods

  • adjacentSum: sum of up, down, left, right neighbors
  • diagonalSum: sum of four diagonal neighbors
  • both use safeGet to handle out-of-bounds gracefully

complexity

O(mn) time to find target value, O(1) for neighbor sums. O(mn) space for grid and prefix arrays.