- 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
- 39 lines of Python from the credited upstream file 2132.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 possibleToStamp(3 self,4 grid: list[list[int]],5 stampHeight: int,6 stampWidth: int,7 ) -> bool:8 m = len(grid)9 n = len(grid[0])10 11 A = [[0] * (n + 1) for _ in range(m + 1)]12 13 B = [[0] * (n + 1) for _ in range(m + 1)]14 15 fit = [[False] * n for _ in range(m)]16 17 for i in range(m):18 for j in range(n):19 A[i + 1][j + 1] = A[i + 1][j] + A[i][j + 1] - A[i][j] + grid[i][j]20 if i + 1 >= stampHeight and j + 1 >= stampWidth:21 x = i - stampHeight + 122 y = j - stampWidth + 123 if A[i + 1][j + 1] - A[x][j + 1] - A[i + 1][y] + A[x][y] == 0:24 fit[i][j] = True25 26 for i in range(m):27 for j in range(n):28 B[i + 1][j + 1] = B[i + 1][j] + B[i][j + 1] - B[i][j] + fit[i][j]29 30 for i in range(m):31 for j in range(n):32 if not grid[i][j]:33 x = min(i + stampHeight, m)34 y = min(j + stampWidth, n)35 if B[x][y] - B[i][y] - B[x][j] + B[i][j] == 0:36 return False37 38 return True39