Count Submatrices With Equal Frequency of X and Y - Problem
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](top-left corner)- An equal frequency of
'X'and'Y' - At least one
'X'
A submatrix is defined by its top-left corner at (0, 0) and bottom-right corner at (i, j) where 0 ≤ i < m and 0 ≤ j < n.
Input & Output
Example 1 — Basic Case
$
Input:
grid = [["X","Y","."],[".","Y","X"]]
›
Output:
3
💡 Note:
Valid submatrices: (0,0) to (0,1) has X=1,Y=1; (0,0) to (1,2) has X=2,Y=2; (0,0) to (1,1) has X=1,Y=2 (invalid)
Example 2 — Single Cell
$
Input:
grid = [["X"]]
›
Output:
0
💡 Note:
Only submatrix is (0,0) to (0,0) with X=1,Y=0. Not equal counts, so 0 valid submatrices
Example 3 — No X Characters
$
Input:
grid = [["Y",".","Y"]]
›
Output:
0
💡 Note:
No submatrix contains at least one X, so result is 0
Constraints
- 1 ≤ grid.length, grid[i].length ≤ 100
- grid[i][j] is either 'X', 'Y', or '.'
Visualization
Tap to expand
Understanding the Visualization
1
Input Grid
2D matrix with X, Y, and dot characters
2
Check Submatrices
All submatrices from (0,0) to various endpoints
3
Count Valid
Those with equal X,Y counts and at least one X
Key Takeaway
🎯 Key Insight: Use prefix sums to calculate submatrix character counts in O(1) time instead of O(mn) repeated counting
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code