1692. Solid Rectangle Count

A tile floor is described by the matrix grid, where 1 marks a sound tile and 0 a cracked one. A repair crew can only lay out a mosaic on an axis-aligned rectangular block made entirely of sound tiles; every distinct block position and size counts separately, and a single sound tile is already a block. Return, as a long, how many such all-ones submatrices exist in grid. The two rectangles are different whenever their top-left or bottom-right corners differ. Checking every block directly is far too slow on large floors; the intended solution processes the rows one by one with column heights and a monotonic stack, running in O(m * n) time and O(n) extra space.

Example 1

Input:
grid = [[1,1],[1,1]]
Output:
9
Explanation:

The 2x2 block has 4 single cells, 2 horizontal and 2 vertical dominoes, and the whole square: 9 rectangles.

Example 2

Input:
grid = [[1,0,1],[1,1,1]]
Output:
10
Explanation:

Top row gives 2 single cells; the bottom row gives 3 singles, 2 horizontal pairs and 1 full row; columns 0 and 2 each give one vertical domino: 10 in all.

Example 3

Input:
grid = [[0]]
Output:
0
Explanation:

There is no cell holding a 1, so no solid rectangle exists.

Constraints

1 ≤ m, n and m * n ≤ 2 * 105

grid[i][j] is 0 or 1

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 1,600 msC++ 400 msJava 800 msJavaScript 800 msTypeScript 800 ms

Expected complexity

Time
O(m * n)
Space
O(n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…