3212. Count Submatrices With Equal Frequency of X and Y
Approach
Prefix sum to compute X and Y counts; for each cell check prefix X == prefix Y and X > 0.
Key Techniques
Array problems involve manipulating elements stored in a contiguous block of memory. Key techniques include two-pointer traversal, prefix sums, sliding windows, and in-place partitioning. In C#, arrays are zero-indexed and fixed in size — use List<T> when you need dynamic resizing.
Matrix problems often involve BFS/DFS flood fill, dynamic programming on 2D grids, or spiral/diagonal traversal. For row × column DP, break it into 1D sub-problems column by column. Common pitfalls: boundary checks and modifying the input matrix in-place.
A prefix sum array pre-computes cumulative values so any range query is answered in O(1). The classic sum of range [l, r] = prefix[r+1] - prefix[l]. 2D prefix sums extend this to matrix sub-rectangle queries. Combine with a hash map for "subarray sum equals k" problems.
// Approach: Prefix sum to compute X and Y counts; for each cell check prefix X == prefix Y and X > 0.
// Time: O(mn) Space: O(mn)
public class Solution
{
public int NumberOfSubmatrices(char[][] grid)
{
int m = grid.Length;
int n = grid[0].Length;
int ans = 0;
// x[i,j] := the number of 'X' in grid[0..i)[0..j)
int[,] x = new int[m + 1, n + 1];
// y[i,j] := the number of 'Y' in grid[0..i)[0..j)
int[,] y = new int[m + 1, n + 1];
for (int i = 0; i < m; ++i)
{
for (int j = 0; j < n; ++j)
{
x[i + 1, j + 1] = (grid[i][j] == 'X' ? 1 : 0) + x[i, j + 1] + x[i + 1, j] - x[i, j];
y[i + 1, j + 1] = (grid[i][j] == 'Y' ? 1 : 0) + y[i, j + 1] + y[i + 1, j] - y[i, j];
if (x[i + 1, j + 1] > 0 && x[i + 1, j + 1] == y[i + 1, j + 1])
++ans;
}
}
return ans;
}
}