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: Equal X and Y FrequencyInput GridXY..YXValid SubmatricesXYSubmatrix 1: X=1, Y=1 ✓XY..YXFull Matrix: X=2, Y=2 ✓Requirements: Must contain (0,0), equal X/Y count, at least one XResult: 3 valid submatrices found
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
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