Count Cells in Overlapping Horizontal and Vertical Substrings - 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.

Input & Output

Example 1 — Basic Pattern Match
$ Input: grid = [["a","b"],["b","a"]], pattern = "ab"
Output: 1
💡 Note: Horizontal "ab" at (0,0)→(0,1) and vertical "ab" at (0,0)→(1,0). Cell (0,0) is in both patterns.
Example 2 — No Overlap
$ Input: grid = [["a","b"],["c","d"]], pattern = "ab"
Output: 0
💡 Note: Horizontal "ab" exists at (0,0)→(0,1) but no vertical "ab" pattern, so no overlapping cells.
Example 3 — Multiple Overlaps
$ Input: grid = [["x","y"],["x","y"]], pattern = "xy"
Output: 2
💡 Note: Both rows contain "xy" horizontally, both columns contain "xy" vertically. Cells (0,0) and (0,1) are in both.

Constraints

  • 1 ≤ m, n ≤ 103
  • 1 ≤ pattern.length ≤ 103
  • grid[i][j] and pattern consist of lowercase English letters

Visualization

Tap to expand
Count Cells in Overlapping Horizontal and Vertical Pattern MatchesabbaGridPattern: "ab"abbaOrange: Overlap CellGreen: Horizontal MatchRed: Vertical MatchCell (0,0) participates in both horizontal "ab" and vertical "ab"Output: 1 overlapping cell
Understanding the Visualization
1
Input
Matrix grid and pattern string to find
2
Process
Find horizontal and vertical pattern matches
3
Output
Count cells in both horizontal and vertical matches
Key Takeaway
🎯 Key Insight: Count cells that are part of BOTH horizontal and vertical pattern occurrences
Asked in
Google 15 Microsoft 12 Amazon 8
12.8K Views
Medium Frequency
~35 min Avg. Time
234 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen