Count Submatrices With Equal Frequency of X and Y Problem
#3212
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3212.
Given a 2D character matrix grid, where grid[i][j] is either 'X', 'Y', or '.', return the number of submatrices that contain:
grid[0][0]- an equal frequency of
'X'and'Y'. - at least one
'X'.
Example 1:
Input: grid = [["X","Y","."],["Y",".","."]]
Output: 3
Explanation:

Example 2:
Input: grid = [["X","X"],["X","Y"]]
Output: 0
Explanation:
No submatrix has an equal frequency of 'X' and 'Y'.
Example 3:
Input: grid = [[".","."],[".","."]]
Output: 0
Explanation:
No submatrix has at least one 'X'.
Constraints:
1 <= grid.length, grid[i].length <= 1000grid[i][j]is either'X','Y', or'.'.
Solution
Approach: 2D Prefix Sums
Every valid submatrix starts at the top-left cell, so each cell (i, j) defines one candidate: the submatrix from (0, 0) to (i, j).
Keep two 2D prefix sums, the number of X and the number of Y in each such submatrix. A cell counts when the X total is positive and equals the Y total.
Complexity: O(mn) time and O(mn) space.
class Solution:
def numberOfSubmatrices(self, grid: List[List[str]]) -> int:
m, n = len(grid), len(grid[0])
s = [[[0] * 2 for _ in range(n + 1)] for _ in range(m + 1)]
ans = 0
for i, row in enumerate(grid, 1):
for j, x in enumerate(row, 1):
s[i][j][0] = s[i - 1][j][0] + s[i][j - 1][0] - s[i - 1][j - 1][0]
s[i][j][1] = s[i - 1][j][1] + s[i][j - 1][1] - s[i - 1][j - 1][1]
if x != ".":
s[i][j][ord(x) & 1] += 1
if s[i][j][0] > 0 and s[i][j][0] == s[i][j][1]:
ans += 1
return ans