- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 45 lines of Python from the credited upstream file 3030.py.
- The implementation visibly relies on sequence storage.
- No explicit loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution:2 def resultGrid(3 self,4 image: list[list[int]],5 threshold: int,6 ) -> list[list[int]]:7 m = len(image)8 n = len(image[0])9 sums = [[0] * n for _ in range(m)]10 counts = [[0] * n for _ in range(m)]11 12 for i in range(m - 2):13 for j in range(n - 2):14 if self._isRegion(image, i, j, threshold):15 subgridSum = sum(image[x][y]16 for x in range(i, i + 3)17 for y in range(j, j + 3))18 for x in range(i, i + 3):19 for y in range(j, j + 3):20 sums[x][y] += subgridSum 921 counts[x][y] += 122 23 for i in range(m):24 for j in range(n):25 if counts[i][j] > 0:26 image[i][j] = sums[i][j] counts[i][j]27 28 return image29 30 def _isRegion(31 self,32 image: list[list[int]],33 i: int,34 j: int,35 threshold: int,36 ) -> bool:37 """Returns True if image[i..i + 2][j..j + 2] is a region."""38 for x in range(i, i + 3):39 for y in range(j, j + 3):40 if x > i and abs(image[x][y] - image[x - 1][y]) > threshold:41 return False42 if y > j and abs(image[x][y] - image[x][y - 1]) > threshold:43 return False44 return True45