3212. Count Submatrices With Equal Frequency of X and Y
UnknownView on LeetCode
Time: O(mn)
Space: O(mn)
Problem Overview
Count Submatrices With Equal Frequency of X and Y (Unknown) asks you to solve a structured algorithmic task. This is a common Array / Matrix pattern in coding interviews. Prefix sum to compute X and Y counts; for each cell check prefix X == prefix Y and X > 0.
A full step-by-step explanation is being added. See the study guide for pattern-based practice.
Approach
Prefix sum to compute X and Y counts; for each cell check prefix X == prefix Y and X > 0.
Related patterns: Array, Matrix, Prefix Sum
3212.cs
C#
// Approach: Prefix sum to compute X and Y counts; for each cell check prefix X == prefix Y and X > 0.
// Time: O(mn) Space: O(mn)
public class Solution
{
public int NumberOfSubmatrices(char[][] grid)
{
int m = grid.Length;
int n = grid[0].Length;
int ans = 0;
// x[i,j] := the number of 'X' in grid[0..i)[0..j)
int[,] x = new int[m + 1, n + 1];
// y[i,j] := the number of 'Y' in grid[0..i)[0..j)
int[,] y = new int[m + 1, n + 1];
for (int i = 0; i < m; ++i)
{
for (int j = 0; j < n; ++j)
{
x[i + 1, j + 1] = (grid[i][j] == 'X' ? 1 : 0) + x[i, j + 1] + x[i + 1, j] - x[i, j];
y[i + 1, j + 1] = (grid[i][j] == 'Y' ? 1 : 0) + y[i, j + 1] + y[i + 1, j] - y[i, j];
if (x[i + 1, j + 1] > 0 && x[i + 1, j + 1] == y[i + 1, j + 1])
++ans;
}
}
return ans;
}
}Was this solution helpful?
Related Problems
- 4. Median of Two Sorted Arrays(Hard)
- 11. Container With Most Water(Medium)
- 15. 3Sum(Medium)
- 16. 3Sum Closest(Medium)
- 26. Remove Duplicates from Sorted Array(Easy)
- 27. Remove Element(Easy)