Problem
You are given an m x n
matrix grid
consisting of characters and a string
pattern
.
A horizontal substring is a contiguous sequence of characters read from left to right. If the end of a row is reached before the substring is complete, it wraps to the first column of the next row and continues as needed. You do not wrap from the bottom row back to the top.
A vertical substring is a contiguous sequence of characters read from top to bottom. If the bottom of a column is reached before the substring is complete, it wraps to the first row of the next column and continues as needed. You do not wrap from the last column back to the first.
Count the number of cells in the matrix that satisfy the following condition:
- The cell must be part of at least one horizontal substring and at least one vertical substring, where both substrings are equal to the given
pattern
.
Return the count of these cells.
Example 1
|
|
Example 2
|
|
Example 3
|
|
Constraints
m == grid.length
n == grid[i].length
1 <= m, n <= 1000
1 <= m * n <= 10^5
1 <= pattern.length <= m * n
grid
andpattern
consist of only lowercase English letters.
Examples
Solution
Method 1 – Rolling Hash and Set Marking 1
Intuition
To efficiently find all horizontal and vertical substrings matching the pattern (with wrapping), we use rolling hash for substring matching. For each match, we mark the cells covered by the substring. Finally, we count the cells that are covered by at least one horizontal and at least one vertical match.
Approach
- Use rolling hash to find all horizontal substrings matching the pattern (with wrapping across rows).
- Use rolling hash to find all vertical substrings matching the pattern (with wrapping across columns).
- For each match, mark the cells covered by the substring in two boolean matrices: one for horizontal, one for vertical.
- Count the number of cells that are marked in both matrices.
Code
|
|
Complexity
- ⏰ Time complexity:
O(mn * k)
, where m, n are grid dimensions and k is the pattern length, as we check all possible starting positions for both directions. - 🧺 Space complexity:
O(mn)
, for the marking matrices.