- 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 Java from the credited upstream file 2132.java.
- The implementation visibly relies on sequence storage.
- 6 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 public boolean possibleToStamp(int[][] grid, int stampHeight, int stampWidth) {3 final int m = grid.length;4 final int n = grid[0].length;5 6 int[][] A = new int[m + 1][n + 1];7 8 int[][] B = new int[m + 1][n + 1];9 10 int[][] fit = new int[m][n];11 12 for (int i = 0; i < m; ++i)13 for (int j = 0; j < n; ++j) {14 A[i + 1][j + 1] = A[i + 1][j] + A[i][j + 1] - A[i][j] + grid[i][j];15 if (i + 1 >= stampHeight && j + 1 >= stampWidth) {16 final int x = i - stampHeight + 1;17 final int y = j - stampWidth + 1;18 if (A[i + 1][j + 1] - A[x][j + 1] - A[i + 1][y] + A[x][y] == 0)19 fit[i][j] = 1;20 }21 }22 23 for (int i = 0; i < m; ++i)24 for (int j = 0; j < n; ++j)25 B[i + 1][j + 1] = B[i + 1][j] + B[i][j + 1] - B[i][j] + fit[i][j];26 27 for (int i = 0; i < m; ++i)28 for (int j = 0; j < n; ++j)29 if (grid[i][j] == 0) {30 final int x = Math.min(i + stampHeight, m);31 final int y = Math.min(j + stampWidth, n);32 if (B[x][y] - B[i][y] - B[x][j] + B[i][j] == 0)33 return false;34 }35 36 return true;37 }38}39