Count Submatrices With Equal Frequency of X and Y - Problem
You're given a 2D character matrix grid where each cell contains either 'X', 'Y', or '.'. Your task is to find the number of submatrices that satisfy all of the following conditions:
- The submatrix must include the top-left corner
grid[0][0] - The submatrix contains an equal frequency of
'X'and'Y'characters - The submatrix contains at least one
'X'character
A submatrix is defined by its bottom-right corner (i, j), where the submatrix includes all cells from (0, 0) to (i, j) inclusive.
Example: If grid[0][0] = 'X' and grid[0][1] = 'Y', then the submatrix ending at (0, 1) has 1 'X' and 1 'Y', satisfying our conditions.
Input & Output
example_1.py β Basic balanced submatrix
$
Input:
grid = [["X","Y"],["Y","X"]]
βΊ
Output:
2
π‘ Note:
Two valid submatrices: (0,0)β(0,1) with 1 X and 1 Y, and (0,0)β(1,1) with 2 X's and 2 Y's
example_2.py β Single cell case
$
Input:
grid = [["X"]]
βΊ
Output:
0
π‘ Note:
Only one submatrix (0,0)β(0,0) with 1 X and 0 Y's - not balanced, so result is 0
example_3.py β Mixed with dots
$
Input:
grid = [["X",".","Y"],[".","Y","X"]]
βΊ
Output:
1
π‘ Note:
Only the full submatrix (0,0)β(1,2) has balanced counts: 2 X's and 2 Y's
Visualization
Tap to expand
Understanding the Visualization
1
Build counting tables
Create cumulative count tables for treasures (X) and traps (Y)
2
Evaluate regions
For each possible rectangular region starting from origin, check balance
3
Apply criteria
Count regions where treasures equal traps and at least one treasure exists
4
Report findings
Return the total count of viable expedition regions
Key Takeaway
π― Key Insight: Prefix sums transform an O(mΒ²ΓnΒ²) brute force solution into an elegant O(mΓn) algorithm by precomputing cumulative counts, enabling instant submatrix queries.
Time & Space Complexity
Time Complexity
O(m Γ n)
O(mΓn) to build prefix sums + O(mΓn) to check all endpoints
β Linear Growth
Space Complexity
O(m Γ n)
Two prefix sum arrays of size mΓn for X and Y counts
β‘ Linearithmic Space
Constraints
- 1 β€ grid.length, grid[i].length β€ 100
- grid[i][j] is either 'X', 'Y', or '.'
- The submatrix must contain grid[0][0]
- At least one 'X' must be present in valid submatrices
π‘
Explanation
AI Ready
π‘ Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code