Magicsheet logo

Count Submatrices With Equal Frequency of X and Y

Medium
37.5%
Updated 8/1/2025

Asked by 1 Company

Count Submatrices With Equal Frequency of X and Y

What is this problem about?

The "Count Submatrices With Equal Frequency of X and Y interview question" is a 2D prefix-sum challenge. You are given a matrix containing characters (like 'X', 'Y', and '.'). You need to count the number of submatrices that start at the top-left corner (0,0)(0, 0) and satisfy two conditions:

  1. The frequency of 'X' is equal to the frequency of 'Y'.
  2. The frequency of 'X' is at least 1.

Why is this asked in interviews?

Microsoft uses the "Count Submatrices With Equal Frequency coding problem" to test a candidate's mastery of 2D Prefix Sums. While general submatrices are hard to count, restricting them to start at (0,0)(0, 0) allows for a linear O(MimesN)O(M imes N) solution. It evaluations your ability to pre-calculate and query 2D areas in constant time.

Algorithmic pattern used

This problem follows the 2D Prefix Sum pattern.

  1. Count Grids: Create two 2D prefix sum arrays: countX[i][j] and countY[i][j].
  2. Formula: The number of 'X's in the rectangle from (0,0)(0, 0) to (i,j)(i, j) is simply the prefix sum at (i,j)(i, j). Unlike general rectangles, you don't need to subtract other areas.
  3. Implementation:
    • Iterate through every possible bottom-right corner (i,j)(i, j).
    • Calculate the number of 'X's and 'Y's in the rectangle (0, 0) to (i, j).
    • If X_count == Y_count AND X_count > 0, increment the result.
  4. Space Optimization: You can calculate the counts on the fly using a 1D array or by updating the matrix itself to save space.

Example explanation

Matrix:

X Y
. X
  • Corner (0,0): X=1, Y=0. Not equal.
  • Corner (0,1): X=1, Y=1. Equal! Count = 1.
  • Corner (1,0): X=1, Y=0. Not equal.
  • Corner (1,1): X=2, Y=1. Not equal. Result: 1.

Common mistakes candidates make

  • Over-complicating: Thinking you need to check ALL submatrices when only those starting at (0,0)(0, 0) are required.
  • Ignoring the "at least one X" rule: Counting empty or '.'-only submatrices where 0==00 == 0.
  • Off-by-one: Mistakes in 2D prefix sum calculations (though much simpler for (0,0)(0, 0) anchored rectangles).

Interview preparation tip

Always read the constraints on submatrices. "Starting at (0, 0)" or "Starting at row 0" are huge hints that the complexity should be O(MimesN)O(M imes N). This is a great "Matrix interview pattern" starter for 2D area problems.

Similar Questions