All problems
0912MediumArrayMatrixPrefix Sum

Corner Blocks With Matching Marks

Tracked in this browser only
Write code

Trains the technique from

LeetCode 3212Count Submatrices With Equal Frequency of X and Y

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

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 is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

Python
def number_of_submatrices(grid: list[list[str]]) -> int:
Java
public int numberOfSubmatrices(char[][] grid)
September 7
Apply