You are given an m ร n matrix grid consisting of characters and a pattern string. Your task is to find cells that are part of both a horizontal and vertical occurrence of the pattern.
Horizontal Reading: Read characters from left to right. When you reach the end of a row, wrap to the first column of the next row and continue. You cannot wrap from the last row back to the first.
Vertical Reading: Read characters from top to bottom. When you reach the bottom of a column, wrap to the first row of the next column and continue. You cannot wrap from the last column back to the first.
Goal: Count cells that belong to at least one horizontal substring AND at least one vertical substring, where both substrings match the given pattern.
Example: If pattern = "AB" and we find "AB" horizontally starting at (0,0) and "AB" vertically starting at (0,0), then cell (0,0) contributes to our count since it's part of both occurrences.
Input & Output
Visualization
Time & Space Complexity
KMP preprocessing is O(p), searching in linearized strings is O(m*n), total is O(m*n + p)
Space for linearized strings O(m*n) plus KMP failure function O(p)
Constraints
- 1 โค m, n โค 100 (matrix dimensions)
- 1 โค pattern.length โค m ร n
- grid[i][j] and pattern consist of lowercase English letters only
- Pattern length does not exceed total matrix size
- No empty inputs: grid, pattern are non-empty