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]'X' and 'Y'.'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 '.'.This approach uses a prefix sum array and a hash map to maintain the difference between the numbers of 'X' and 'Y' found so far. This setup enables the identification of subarrays where the count of 'X' and 'Y' is equal.
For each row start and row end combination, collapse the 2D array into a 1D frequency difference array, and search for differences that occur at least once in different locations, which will correspond to equal X and Y submatrices.
The solution iterates through each possible pair of starting and ending rows. For each column, it calculates the difference between the number of 'X's and 'Y's and updates a hash map to find matches with previous occurrences of the same difference. This identifies submatrices satisfying the problem's condition.
Java
Time Complexity: O(n^2 * m), where n is the number of rows and m is the number of columns.
Space Complexity: O(m), for the hash map storing differences.
This approach uses dynamic programming by maintaining an accumulated count array. The goal is to keep a cumulative total of 'X's and 'Y's up to each point in the grid, allowing quick calculation of any submatrix's contents via differences.
This C++ code uses two 2D arrays to maintain cumulative counts of 'X' and 'Y' appearance. For each valid starting and ending row, it calculates the count differences column-wise and integrates these differences with hash maps to derive submatrices with equal numbers of 'X' and 'Y'.
JavaScript
Time Complexity: O(n * m^2), where n is the number of rows and m is the number of columns.
Space Complexity: O(n * m), for storing cumulative counts.
| Approach | Complexity |
|---|---|
| Prefix Sum and Hash Map | Time Complexity: O(n^2 * m), where n is the number of rows and m is the number of columns. |
| Dynamic Programming with Accumulated Count | Time Complexity: O(n * m^2), where n is the number of rows and m is the number of columns. |
Leetcode 1504. Count Submatrices With All Ones • Fraz • 30,539 views views
Watch 9 more video solutions →Practice Count Submatrices With Equal Frequency of X and Y with our built-in code editor and test cases.
Practice on FleetCode