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 Substrings INPUT 2x2 Grid Matrix "a" "b" "b" "a" (0,0) (0,1) R0 R1 Pattern: "ab" Horizontal: left to right Vertical: top to bottom ALGORITHM STEPS 1 Find Horizontal Matches Scan rows for "ab" pattern a b Match at (0,0) 2 Find Vertical Matches Scan columns for "ab" a b Match at Col 0: (0,0),(1,0) 3 Store in Sets H-set and V-set of cells 4 Intersect Sets Count common cells H-set ∩ V-set = {(0,0)} FINAL RESULT Overlapping Cell Highlighted "a" "b" "b" "a" Cell (0,0) is in BOTH: - Horizontal "ab" match - Vertical "ab" match Output: 1 [OK] 1 overlapping cell Key Insight: The Two-Pass with Sets approach efficiently finds overlapping cells by: 1) First pass: collect all cells in horizontal pattern matches into Set H 2) Second pass: collect all cells in vertical pattern matches into Set V, then return |H intersect V| TutorialsPoint - Count Cells in Overlapping Horizontal and Vertical Substrings | Two-Pass with Sets Approach
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