- 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
- 79 lines of Java from the credited upstream file 3529.java.
- The implementation visibly relies on sequence storage.
- 10 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 int countCells(char[][] grid, String pattern) {3 final int m = grid.length;4 final int n = grid[0].length;5 int ans = 0;6 StringBuilder flattenedGridRow = new StringBuilder();7 StringBuilder flattenedGridCol = new StringBuilder();8 9 10 for (int i = 0; i < m; ++i)11 for (int j = 0; j < n; ++j)12 flattenedGridRow.append(grid[i][j]);13 14 15 for (int j = 0; j < n; ++j)16 for (int i = 0; i < m; ++i)17 flattenedGridCol.append(grid[i][j]);18 19 20 boolean[][] horizontalMatches =21 markMatchedCells(flattenedGridRow.toString(), pattern, m, n, true);22 boolean[][] verticalMatches =23 markMatchedCells(flattenedGridCol.toString(), pattern, m, n, false);24 25 26 for (int i = 0; i < m; ++i)27 for (int j = 0; j < n; ++j)28 if (horizontalMatches[i][j] && verticalMatches[i][j])29 ++ans;30 31 return ans;32 }33 34 private static final long BASE = 13;35 private static final long HASH = 1_000_000_007;36 37 private boolean[][] markMatchedCells(final String flattenedGrid, final String pattern, int m,38 int n, boolean isHorizontal) {39 boolean[][] matchMatrix = new boolean[m][n];40 int[] matchPrefix = new int[flattenedGrid.length() + 1];41 long[] pows = new long[pattern.length()]; 42 pows[0] = 1;43 long patternHash = 0;44 long runningHash = 0;45 46 for (int i = 1; i < pattern.length(); ++i)47 pows[i] = (pows[i - 1] * BASE) % HASH;48 49 for (final char c : pattern.toCharArray())50 patternHash = (patternHash * BASE + (c - 'a')) % HASH;51 52 for (int i = 0; i < flattenedGrid.length(); ++i) {53 runningHash = (runningHash * BASE + (flattenedGrid.charAt(i) - 'a')) % HASH;54 if (i >= pattern.length() - 1) {55 if (runningHash == patternHash) { 56 ++matchPrefix[i - pattern.length() + 1];57 --matchPrefix[i + 1];58 }59 60 final long oldestLetterHash =61 (pows[pattern.length() - 1] * (flattenedGrid.charAt(i - pattern.length() + 1) - 'a')) %62 HASH;63 runningHash = (runningHash - oldestLetterHash + HASH) % HASH;64 }65 }66 67 for (int k = 0; k < flattenedGrid.length(); ++k) {68 matchPrefix[k] += (k > 0) ? matchPrefix[k - 1] : 0;69 if (matchPrefix[k] > 0) {70 final int i = isHorizontal ? k / n : k % m;71 final int j = isHorizontal ? k % n : k / m;72 matchMatrix[i][j] = true;73 }74 }75 76 return matchMatrix;77 }78}79