- 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
- 52 lines of Python from the credited upstream file 3529.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 countCells(self, grid: list[list[str]], pattern: str) -> int:3 BASE = 134 HASH = 1_000_000_0075 m = len(grid)6 n = len(grid[0])7 8 def markMatchedCells(flattenedGrid: str, isHorizontal: bool) -> list[list[bool]]:9 matchMatrix = [[False] * n for _ in range(m)]10 matchPrefix = [0] * (len(flattenedGrid) + 1)11 pows = [1] 12 patternHash = 013 runningHash = 014 15 for i in range(1, len(pattern)):16 pows.append((pows[-1] * BASE) % HASH)17 18 for c in pattern:19 patternHash = (patternHash * BASE + (ord(c) - ord('a'))) % HASH20 21 for i in range(len(flattenedGrid)):22 runningHash = (23 runningHash * BASE + (ord(flattenedGrid[i]) - ord('a'))) % HASH24 if i >= len(pattern) - 1:25 if runningHash == patternHash: 26 matchPrefix[i - len(pattern) + 1] += 127 matchPrefix[i + 1] -= 128 29 oldestLetterHash = (30 pows[len(pattern) - 1] *31 (ord(flattenedGrid[i - len(pattern) + 1]) - ord('a'))) % HASH32 runningHash = (runningHash - oldestLetterHash + HASH) % HASH33 34 for k in range(len(flattenedGrid)):35 if k > 0:36 matchPrefix[k] += matchPrefix[k - 1]37 if matchPrefix[k] > 0:38 i = k n if isHorizontal else k % m39 j = k % n if isHorizontal else k m40 matchMatrix[i][j] = True41 42 return matchMatrix43 44 45 flattenedGridRow = ''.join(cell for row in grid for cell in row)46 flattenedGridCol = ''.join(cell for col in zip(*grid) for cell in col)47 horizontalMatches = markMatchedCells(flattenedGridRow, True)48 verticalMatches = markMatchedCells(flattenedGridCol, False)49 return sum(horizontalMatches[i][j] and verticalMatches[i][j]50 for i in range(m)51 for j in range(n))52