Problem Description
Given a 2D character matrix grid, where each cell is either 'X', 'Y', or '.', count the number of submatrices that:
- Contain the cell grid[0][0] (i.e. the top‐left cell must be included).
- Have an equal frequency of 'X' and 'Y'.
- Contain at least one 'X'.
Since any submatrix that contains grid[0][0] must have its upper‐left corner at (0,0), the problem reduces to counting the number of prefixes (submatrices defined by (0,0) to (i,j)) that meet the other two conditions.
Key Insights
- Because grid[0][0] must be inside the submatrix, all valid submatrices are prefixes starting at (0,0) and extending to some (i,j).
- For a prefix submatrix from (0,0) to (i,j), the count of 'X' and 'Y' can be computed incrementally.
- The conditions translate to:
- (# of 'X') equals (# of 'Y') in the prefix.
- (# of 'X') is at least 1 (to ensure that the submatrix contains at least one 'X').
- A simple two-dimensional iterative approach with cumulative counts is sufficient given the input constraints.
Space and Time Complexity
Time Complexity: O(m * n) where m and n are the number of rows and columns. Space Complexity: O(1) extra space (if we do it in one pass without using extra matrices)
Solution
We use a straightforward approach with two nested loops to examine each prefix submatrix defined by top-left (0,0) and bottom-right (i,j). For each such prefix we keep a running count of the number of 'X' and 'Y'.
- As we iterate through the grid, update cumulative counts for X and Y.
- For each cell (i,j), if the cumulative count of 'X' equals that of 'Y' and is non-zero (which ensures at least one 'X' exists), we increment our answer.
- The algorithm is efficient due to processing each cell exactly once.
Note: Although prefix sum arrays are common for submatrix sum problems, here the submatrix is fixed to start at (0,0) so we can accumulate counts directly in a double loop.