The Count Cells in Overlapping Horizontal and Vertical Substrings interview question involves a 2D grid of characters. You are given a target string P. You need to count how many cells (r, c) in the grid are part of at least one horizontal occurrence of P AND at least one vertical occurrence of P.
Google asks this Matrix interview pattern to evaluate your string matching and grid traversal efficiency. It’s a "Medium" problem because you must avoid redundant checks. It tests whether you can use boolean matrices to mark "covered" cells and whether you can efficiently find occurrences of a pattern in both rows and columns.
The problem uses String Matching (KMP or Rolling Hash) and Matrix Marking.
horizontal_covered and vertical_covered.indexOf or KMP) to find all occurrences of P. Mark all cells in those occurrences in horizontal_covered.vertical_covered.horizontal_covered[r][c] and vertical_covered[r][c] are both true.Grid:
A B A
B A B
A B A
Pattern P = "ABA"
ABA found. Mark (0,0), (0,1), (0,2) in H_map.ABA found. Mark (2,0), (2,1), (2,2) in H_map.ABA found. Mark (0,0), (1,0), (2,0) in V_map.ABA found. Mark (0,2), (1,2), (2,2) in V_map.
Overlapping cells: (0,0), (0,2), (2,0), (2,2).
Result: 4.When working with grid patterns, always think about "Marking." Instead of calculating complex overlaps, use a simple boolean array to track which cells meet each individual condition.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Number of Subarrays That Match a Pattern I | Medium | Solve | |
| Count Prefix and Suffix Pairs I | Easy | Solve | |
| Minimum Time to Revert Word to Initial State I | Medium | Solve | |
| Count Prefix and Suffix Pairs II | Hard | Solve | |
| Longest Happy Prefix | Hard | Solve |