Count Submatrices With Equal Frequency of X and Y

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]
  • an equal frequency of 'X' and 'Y'
  • at least one 'X'
Example 1
X Y .
Y . .
Inputgrid = [["X","Y","."],["Y",".","."]]
Output3
The valid submatrices containing grid[0][0] are the top-left anchored rectangles ending at (0, 1), (0, 2), and (1, 0).
Example 2
X X
X Y
Inputgrid = [["X","X"],["X","Y"]]
Output0
No submatrix has an equal frequency of 'X' and 'Y'.

Constraints

  • 1 <= grid.length, grid[i].length <= 1000
  • grid[i][j] is either 'X', 'Y', or '.'.

Asked at 3 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate