Count Submatrices With Equal Frequency of X and Y
Real-world version: Corner Blocks With Matching MarksThe statement here is our own: the same inputs, outputs and technique.
A board is given as grid, each cell holding 'X', 'Y' or '.'.
A corner block is a rectangle of cells whose top-left cell is the board's own top-left cell. A corner block balances when it holds as many 'X' marks as 'Y' marks and holds at least one 'X'.
Return how many corner blocks balance.
Examples
Example 1
- Input
- grid = [["X", ".", "Y", "X"], [".", "Y", "X", "."], ["Y", "X", ".", "Y"]]
- Output
- 7
Each corner block is named by its bottom-right cell. Those whose X and Y counts come out level, with at least one X present, are the ones counted.
Example 2
- Input
- grid = [["X", "Y"]]
- Output
- 1
The block ending at the first cell holds one X and no Y, so it does not balance. The block covering both cells holds one of each, so it does.
Example 3
- Input
- grid = [["."]]
- Output
- 0
The only block holds no X at all, so nothing balances.
Constraints
- 1 <= grid.length <= 1000
- 1 <= grid[i].length <= 1000
- Every row of grid has the same length
- grid[i][j] is 'X', 'Y' or '.'
The signature
The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.
def number_of_submatrices(grid: list[list[str]]) -> int:public int numberOfSubmatrices(char[][] grid)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 11 test cases: 11 passed
- Passed: 3 worked examples confirmed by running the code
- Passed: 0 eight-word sequences shared with the parent problem's text
- Passed: Agrees with an independent brute-force solution on random inputs
- Passed: Test set shown to catch deliberately broken solutions
- Passed: Reviewed by a separate quality pass
- Passed: Function arity matches the parent problem's
More on the same topics
- Equal Sum Grid Partition IReal-world version: Splitting the Yield Plot in TwoMedium
- Matrix Block SumReal-world version: Neighbourhood Totals On A Sensor PanelMedium
- Construct Product MatrixReal-world version: Cross Product PanelMedium
- Get Biggest Three Rhombus Sums in a GridReal-world version: Three Best Diamond Outlines on a BoardMedium