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
Count Submatrices With Equal Frequency of X and Y INPUT 2D Character Grid (2x3) X (0,0) Y (0,1) . (0,2) . (1,0) Y (1,1) X (1,2) Submatrix Rules: • Start from (0,0) • End at any (i,j) • Count(X) == Count(Y) • At least one X ALGORITHM STEPS 1 Build Prefix Sums Track X count, Y count 2 For each (i,j) Calculate prefix sums 3 Check Conditions X==Y and X>=1 4 Count Valid Increment result Prefix Count Table pos X Y Valid (0,0) 1 0 No (0,1) 1 1 OK (1,1) 1 2 No (1,2) 2 2 OK FINAL RESULT 3 Valid Submatrices Found #1: (0,0) to (0,1) X Y X:1 Y:1 #2: (0,0) to (0,2) to (1,2) X Y . X:1 Y:1 #3: Full grid (0,0) to (1,2) X Y . . Y X X:2 Y:2 OUTPUT 3 Key Insight: Use 2D prefix sums to track cumulative X and Y counts. For each position (i,j), we can compute the total X and Y in the submatrix from (0,0) to (i,j) in O(1) time. A submatrix is valid when countX == countY AND countX >= 1. Time: O(m*n), Space: O(m*n) for prefix arrays. TutorialsPoint - Count Submatrices With Equal Frequency of X and Y | Optimal Solution with Prefix Sums
Asked in
Google 25 Microsoft 18 Amazon 15
12.5K Views
Medium Frequency
~25 min Avg. Time
342 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen