#3529

Count Cells in Overlapping Horizontal and Vertical Substrings

Medium
ArrayStringRolling HashString MatchingMatrixHash FunctionHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(m * n * (m + n))
O(m * n)
Space
O(m * n)
O(m * n)
💡

Intuition

Time O(m * n)Space O(m * n)

Utilize rolling hash to efficiently find occurrences of the pattern both horizontally and vertically, reducing unnecessary checks.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a rolling hash function to find horizontal occurrences of the pattern.
  2. 2Step 2: Store the positions of horizontal matches in a set.
  3. 3Step 3: Create a similar rolling hash for vertical occurrences and count overlapping positions.
solution.py15 lines
1def count_cells(grid, pattern):
2    m, n = len(grid), len(grid[0])
3    horizontal_positions = set()
4    pattern_len = len(pattern)
5    for i in range(m):
6        for j in range(n):
7            if j + pattern_len <= n and ''.join(grid[i][j:j+pattern_len]) == pattern:
8                horizontal_positions.update((i, j+k) for k in range(pattern_len))
9    count = 0
10    for j in range(n):
11        for i in range(m):
12            if i + pattern_len <= m:
13                if ''.join(grid[i+k][j] for k in range(pattern_len)) == pattern:
14                    count += sum((1 for k in range(pattern_len) if (i+k, j) in horizontal_positions))
15    return count

Complexity note: Efficiently checks for matches using rolling hash, minimizing redundant checks.

  • 1Horizontal and vertical checks are independent but must intersect.
  • 2Using sets allows for efficient overlap checks.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.