Problem Description
Given an n x n grid with distinct elements in the range [0, n² - 1], implement a NeighborSum service that can efficiently compute:
- The sum of adjacent neighbors (up, down, left, right) for a given value.
- The sum of diagonal neighbors (top-left, top-right, bottom-left, bottom-right) for a given value.
Key Insights
- Use a hash map (dictionary) to map each grid value to its corresponding (row, col) position for constant time lookups.
- Define directional delta arrays for adjacent and diagonal neighbors.
- Handle boundary conditions to ensure only valid grid indices are considered.
- Preprocess the grid in O(n²) time so that each neighbor sum query can be answered in O(1) time.
Space and Time Complexity
Time Complexity: O(1) per query after O(n²) preprocessing. Space Complexity: O(n²) due to the value-to-coordinate mapping.
Solution
We start by preprocessing the grid to create a mapping from each value to its (row, col) location. This allows us to quickly locate the target value when a query is made. For each query (adjacentSum or diagonalSum), we:
- Retrieve the coordinates of the given value using our map.
- Iterate through the appropriate directional arrays (adjacent or diagonal).
- Check if the neighbor coordinates are within the grid boundaries; if so, add the neighbor's value. This allows the neighbor sum operations to be computed in constant time, leveraging the preprocessing step.
Code Solutions
Below are code implementations in Python, JavaScript, C++, and Java.