1160. Uniform Rectangles

Medium3.5 points estimatedMonotonic StackMatrixCounting

A mosaic is an m x n grid, and grid[i][j] is the digit shown by the tile in row i and column j. A block is any rectangle made of consecutive rows and consecutive columns, from a single tile up to the whole mosaic. Two blocks are different when their row range or their column range differs.

Return how many blocks have all of their tiles showing the same digit, as a 64-bit integer. Constraints: 1 <= m, n, m * n <= 10^5 and 0 <= grid[i][j] <= 9. Trying every block is far too slow; aim for O(m * n) time and O(n) extra space.

Example 1

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

All 9 sub-rectangles of the 2 x 2 block (4 cells, 2 + 2 dominoes and the whole block) are uniform.

Example 2

Input:
grid = [[1,2],[3,4]]
Output:
4
Explanation:

Only the 4 single cells are uniform.

Example 3

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

The left 2 x 2 block gives 9 rectangles and the right column gives 3 more, 12 in all.

Constraints

1 ≤ m, n
m * n ≤ 105
0 ≤ grid[i][j] ≤ 9

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 2,000 msC++ 500 msJava 1,000 msJavaScript 1,000 msTypeScript 1,000 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…