We are given a 2D grid of integers. We need to find the number of "rectangles" of 1's. Usually, in such problems, a rectangle of 1's means a submatrix that is entirely filled with 1's. But sometimes they mean rectangles formed by 1's that are contiguous? The problem statement says "rectangles of 1s". Typically, it means any axis-aligned rectangle (submatrix) that contains only 1's. We count all possible such rectangles. For example, if we have a grid:
grid = [
[1, 0, 1],
[1, 1, 0],
[0, 1, 1]
]
How many rectangles of 1's? We need to consider all possible subrectangles (contiguous blocks) that are all 1s. That includes 1x1, 1x2, 2x2, etc. But note: a rectangle must be axis-aligned and contiguous. Usually we count all such submatrices that are all ones.
But sometimes the problem might ask for "rectangles" meaning that the four corners are 1 and the interior can be anything? That is a different problem. But here it says "rectangles of 1s", which likely means rectangles composed entirely of 1s. I'll assume that.
So we need to count the number of submatrices that consist entirely of 1s.
Given a grid of size m x n, we want an efficient algorithm. The naive approach would be to consider all possible top-left and bottom-right corners and check the submatrix, which would be O(m^2 * n^2 * area) which is too slow.
Better approach: we can preprocess the grid to compute for each cell (i, j) the number of consecutive 1s to the right (or down) but that might not directly give rectangles. A common method for counting all-ones submatrices is to use the histogram method. For each row, we can consider it as the base and compute the "height" of consecutive ones above including current row. Then for each row, we have an array of heights (like in "largest rectangle in histogram" problem). But we want to count all possible rectangles, not just the maximum area.
Actually, there is a known algorithm to count the number of all-ones submatrices in O(mn) or O(mn^2) etc. One approach:
Let dp[i][j] be the number of all-ones submatrices ending at (i, j) as the bottom-right corner. But that is not straightforward because a rectangle ending at (i,j) can have various top-left corners.
Alternatively, we can iterate over all pairs of rows (top and bottom) and for each column, check if all entries between these rows are 1. Then we have a 1D array of columns where the vertical strip is all ones. Then the number of rectangles between these two rows is the number of subarrays of consecutive 1s in that 1D array. So for each pair of rows (i, j) with i <= j, we can compute an array valid_cols[k] = 1 if for all rows from i to j, grid[row][k] == 1. Then the number of rectangles that have top row i and bottom row j is the number of contiguous subarrays of 1s in valid_cols. That can be computed in O(n) for each pair. So total time O(m^2 * n). Since m and n can be up to? Not specified, but O(m^2 n) might be acceptable if grid is moderate. But if m and n are large (like 1000), then m^2 n could be 10^9 which is too high. But we might improve.
Alternatively, we can do O(mn) by a more clever method? Actually, there is an algorithm to count all-ones submatrices in O(mn) using dynamic programming and stack? Not sure.
Let's consider: For each cell (i, j), we can compute h[i][j] = number of consecutive ones vertically above (including current) i.e., if grid[i][j] == 1 then h[i][j] = h[i-1][j] + 1 else 0. Then for each row i, we have an array h[i] of heights. Now, the number of all-ones submatrices that have bottom row at i can be computed by considering all submatrices that end at row i. For a fixed bottom row i, we want to count all rectangles that have bottom edge at row i. That means for each possible top row, we need to consider the minimum height across the columns in the width. Actually, we can think: a rectangle ending at row i is defined by its top row and left and right columns. But we can also think: for each column j, we consider it as the right edge? Alternatively, we can use the idea from "count submatrices with all ones" which is a known leetcode problem (1504. Count Submatrices With All Ones). Indeed, that problem asks: Given an m x n binary matrix, return the number of submatrices that have all ones. And there are solutions in O(mn) and O(mn^2). Let's recall.
The problem: "Count Submatrices With All Ones" (Leetcode 1504). The constraints: m, n <= 150. So O(m^2 n) is acceptable. But if we want a more efficient solution, there is an O(mn) solution using monotonic stack? Actually, I think there is an O(mn) solution: For each row, we compute the consecutive ones to the left (or right) and then for each cell, we accumulate. Wait, let's derive.
One approach: For each cell (i, j), let left[i][j] = number of consecutive ones to the left including itself, i.e., if grid[i][j]==1 then left[i][j] = left[i][j-1] + 1 else 0. Then for each cell, we can look upwards and for each row above, we take the minimum left value in that column range. But that would be O(m^2 n). But we can optimize by using a stack.
Actually, there is an O(mn) solution: For each row, we compute the histogram of consecutive ones above (h[i][j]). Then for each row, we want to compute the sum of the number of all-ones submatrices that end at this row. That sum can be computed using a monotonic stack to accumulate counts. But I'm not sure if that gives O(mn) total.
Let's think: For a given row i, we have heights h[i][j] for each column j. We want to count all submatrices that have bottom row exactly i. That means we consider all intervals [l, r] on columns and the height of the rectangle is at most the minimum h[i][k] for k in [l, r]. But the rectangle's top row can be any row from i - min_height + 1 to i? Actually, if we have a submatrix with bottom row i and top row t (t <= i), then for each column in the width, the height from t to i must be at least (i-t+1). That means the minimum h[i][k] over the width must be at least (i-t+1). So for a fixed width [l, r], the number of possible top rows is min_{k in [l,r]} h[i][k]. Because if the minimum height is H, then we can choose any top row from i-H+1 to i, giving H choices. But wait, that counts rectangles that have bottom row i and any top row within the range of heights. But careful: For a fixed bottom row i and a fixed column interval [l, r], the submatrix is defined by its top row t and bottom row i. The condition is that for every column k in [l,r], the vertical segment from t to i must be all ones. That means that for each k, h[i][k] >= (i-t+1). So t must satisfy t >= i - h[i][k] + 1 for all k. So the maximum allowed t (closest to i) is i, and the minimum allowed t is i - min_{k} h[i][k] + 1. So the number of possible t is min_{k} h[i][k]. So indeed, for each contiguous interval of columns [l, r], the number of submatrices with bottom row i and that width is min_height = min(h[i][l..r]). So the total number of submatrices with bottom row i is sum over all intervals [l, r] of min(h[i][l..r]). That is exactly the sum of minimums of all subarrays of the array h[i]. That sum can be computed in O(n) using a monotonic stack. So for each row, we can compute sum_{all subarrays} min(subarray) for the array h[i]. That gives the number of submatrices that have bottom row exactly i. Then we sum over all rows.
Thus, the total time is O(m * n) because for each row we do one pass with a stack to compute the sum of minimums of all subarrays. That stack method is standard: given an array A, compute sum of min of all subarrays. We can compute using previous less element and next less element. For each element A[j], we find the number of subarrays where A[j] is the minimum. That is (j - left) * (right - j) where left is index of previous less element, right is index of next less element (or boundaries). Then contribution is A[j] * (j-left)*(right-j). But careful: if there are duplicates, we need to handle properly to avoid double counting. Usually we use strict less on one side and less-or-equal on the other to ensure each subarray's minimum is counted exactly once. For sum of minimums, we can use: for each j, let L[j] be the index of the previous element that is strictly less than A[j] (or -1 if none), and R[j] be the index of the next element that is less than or equal to A[j] (or n if none). Then the number of subarrays where A[j] is the minimum is (j - L[j]) * (R[j] - j). Then sum += A[j] * (j - L[j]) * (R[j] - j). That works for sum of minimums. Alternatively, we can use <= on left and < on right. It's symmetric.
So the algorithm:
- Precompute h[i][j]: for each cell, if grid[i][j]==1, h[i][j] = (i>0 ? h[i-1][j] : 0) + 1 else 0.
- For each row i from 0 to m-1:
- Let arr = h[i] (array of length n)
- Compute sum of min of all subarrays of arr using monotonic stack to get L and R arrays.
- Add that sum to total count.
- Return total.
But wait: does this count all submatrices? Let's test with a small example.
Example 1:
grid = [[1,0,1],[1,1,0],[0,1,1]]
Compute h:
Row0: [1,0,1]
Row1: [2,1,0] (because grid[1][0]=1 so 1+1=2, grid[1][1]=1 so 0+1=1, grid[1][2]=0 so 0)
Row2: [0,2,1] (grid[2][0]=0 so 0, grid[2][1]=1 so 1+1? Actually h[2][1] = if grid[2][1]==1 then h[1][1]+1 = 1+1=2, yes. grid[2][2]=1 so h[1][2] was 0 so 1)
Now for each row:
Row0: arr=[1,0,1]
Subarrays and min:
[0]: min=1? Actually index0:1, index1:0, index2:1.
All subarrays:
[0]: min=1
[0,1]: min=0
[0,1,2]: min=0
[1]: min=0
[1,2]: min=0
[2]: min=1
Sum = 1+0+0+0+0+1 = 2.
But what rectangles have bottom row 0? They are single cells at (0,0) and (0,2) because bottom row is row0. That's 2. So correct.
Row1: arr=[2,1,0]
Subarrays:
Indices:0:2,1:1,2:0.
All subarrays:
[0]: min=2
[0,1]: min=1
[0,1,2]: min=0
[1]: min=1
[1,2]: min=0
[2]: min=0
Sum = 2+1+0+1+0+0 = 4.
What rectangles have bottom row 1? They are:
- 1x1 at (1,0): that's a rectangle.
- 1x1 at (1,1): that's a rectangle.
- 2x1 rectangle from (0,0) to (1,0): that's two cells, bottom row 1, top row 0. That corresponds to subarray [0] with min=2 meaning we can have top rows? Actually for subarray [0] (single column), min=2 so there are 2 possible top rows: row1 (height1) and row0 (height2). That gives two rectangles: 1x1 at (1,0) and 2x1 from (0,0)-(1,0). So that accounts for 2.
For subarray [1] (single column), min=1 so one rectangle: 1x1 at (1,1).
For subarray [0,1]: min=1 so we can have top row at row1 only? Actually min=1 means the height is at least 1, so we can have top row at row1 (height1) giving a 1x2 rectangle at row1 only? But wait, we need to check if the rectangle with bottom row1 and top row1 and columns 0-1 is all ones? That is the submatrix row1, cols0-1: [1,1] yes. That's one rectangle. Could we have top row0? That would require height2 for both columns, but column1 has h[1][1]=1, so not. So only one rectangle from [0,1]. So total for row1: from [0]:2, [1]:1, [0,1]:1, total 4. That matches.
Also note that there is no rectangle that includes column2 because grid[1][2]=0.
Row2: arr=[0,2,1]
Subarrays:
Indices:0:0,1:2,2:1.
All subarrays:
[0]: min=0
[0,1]: min=0
[0,1,2]: min=0
[1]: min=2
[1,2]: min=1
[2]: min=1
Sum = 0+0+0+2+1+1 = 4.
Rectangles with bottom row2:
- Single cell at (2,1): h=2 so two possibilities? Wait bottom row2, column1: h[2][1]=2. That means we can have top row2 (height1) and top row1 (height2). So that gives two rectangles: 1x1 at (2,1) and 2x1 from (1,1)-(2,1). But also we can have column2: h[2][2]=1 gives one rectangle: 1x1 at (2,2).
Also the subarray [1,2]: min=1, so we can have top row2 only? That gives a 1x2 rectangle at row2: (2,1)-(2,2). That's one more.
Also subarray [1]: min=2 gives two rectangles (as above).
Subarray [2]: min=1 gives one rectangle.
So total: from [1]:2, [2]:1, [1,2]:1, total 4. That matches.
So overall total = 2+4+4=10.
Let's list all rectangles manually to verify:
1x1: (0,0), (0,2), (1,0), (1,1), (2,1), (2,2) -> 6.
1x2: row1 cols0-1: (1,0)-(1,1); row2 cols1-2: (2,1)-(2,2) -> 2.
2x1: col0 rows0-1; col1 rows1-2 -> 2.
2x2: is there any? Check rows1-2 and cols1-2: submatrix [[1,0],[1,1]] has a 0, so no. rows0-1 cols0-1: [[1,0],[1,1]] has 0. So no.
Total 6+2+2=10. Yes.
So algorithm works.
Now complexity: O(mn) for computing h, and for each row we do O(n) for sum of minimums using stack. Actually the stack method for sum of min of all subarrays is O(n) per row. So total O(mn). That's efficient.
But wait: The stack method for sum of minimums: we need to compute for each element the number of subarrays where it is the minimum. That requires finding previous less and next less (or previous less-or-equal and next less). That can be done in O(n) with a stack. So overall O(m*n).
So we can implement in O(m*n) time and O(n) extra space per row (or we can reuse).
Edge cases: grid might be empty. We should handle.
Now, we need to write a function. Let's assume the grid is given as a list of lists of integers (0 or 1). We'll write a function count_rectangles(grid) that returns the number.
But note: the problem says "rectangles of 1s". Could it be that they mean rectangles formed by 1s such that the four corners are 1? That is a different problem: count the number of axis-aligned rectangles where all four corners are 1. That is also a common problem. But the phrasing "rectangles of 1s" is ambiguous. However, in the context of "rectangles of 1s", it usually means submatrices filled with 1s. Also, if they meant only corners, they might say "rectangles with all four corners as 1" or "rectangles formed by 1s". But let's check: if they meant only corners, then interior can be anything. That problem is: given a binary matrix, count the number of axis-aligned rectangles such that all four corners are 1. That can be solved by for each pair of rows, count the number of columns where both rows have 1, and then number of rectangles from those columns is C(k,2). That gives O(m^2 n) or O(m n) with optimization. But our algorithm above counts all-ones submatrices, which is a different count.
Which one is more likely? The problem statement: "You are given a 2D grid of integers. Write a function to find the number of 'rectangles' of 1s." It doesn't specify if the rectangle must be entirely filled with 1s or just the corners. In many coding interview questions, "count submatrices with all ones" is a common problem. Also, "rectangles of 1s" might imply the whole rectangle is made of 1s. But sometimes they say "rectangles consisting entirely of 1s". However, the problem statement is terse.
Given that the user said "Please write a function that solves this problem, and explain your algorithm." I should provide a solution and explanation. I'll assume the common interpretation: count all submatrices that are entirely filled with 1s. If the user meant something else, they can clarify.
But let's see if there is any hint: they said "rectangles" in quotes. Maybe it's to emphasize that we are counting rectangles that are made of 1s. I think it's the all-ones submatrices.
I'll go with that.
Now, we need to write a function in some language? Probably Python. I'll write in Python.
Implementation details:
Step 1: Compute h. For each row i, for each col j:
if grid[i][j] == 1: h[i][j] = (h[i-1][j] if i>0 else 0) + 1
else: h[i][j] = 0
But we don't need to store the whole h matrix if we process row by row. We can have a 1D array heights of length n, initialized to 0. Then for each row i, we update: for j in range(n): if grid[i][j]==1: heights[j] += 1 else: heights[j] = 0. Then we have the current row's heights. Then we compute the sum of minimums of all subarrays of this heights array. That sum is the number of submatrices ending at row i.
So we can do:
def count_rectangles(grid):
if not grid or not grid[0]:
return 0
m, n = len(grid), len(grid[0])
heights = [0] * n
total = 0
for i in range(m):
for j in range(n):
if grid[i][j] == 1:
heights[j] += 1
else:
heights[j] = 0
# Now compute sum of min of all subarrays of heights
total += sum_of_subarray_mins(heights)
return total
Now we need sum_of_subarray_mins(arr). Implement using monotonic stack.
Function sum_of_subarray_mins(arr):
n = len(arr)
# We'll compute left boundaries: for each i, find previous index where arr[prev] < arr[i] (strictly less) to avoid duplicates counting multiple times? Actually we need to decide the rule so that each subarray's minimum is counted exactly once.
# Standard approach: For each element arr[i], let left[i] be the index of the previous element that is strictly less than arr[i]. If none, left[i] = -1.
# Let right[i] be the index of the next element that is less than or equal to arr[i]. If none, right[i] = n.
# Then number of subarrays where arr[i] is the minimum = (i - left[i]) * (right[i] - i)
# Then sum += arr[i] * (i - left[i]) * (right[i] - i)
# Alternatively, we can use <= on left and < on right. Both work if consistent. We'll use strict < on left and <= on right.
stack = []
left = [-1] * n
for i in range(n):
while stack and arr[stack[-1]] >= arr[i]: # we want strictly less on left, so we pop until top < arr[i]
stack.pop()
left[i] = stack[-1] if stack else -1
stack.append(i)
stack = []
right = [n] * n
for i in range(n-1, -1, -1):
while stack and arr[stack[-1]] > arr[i]: # we want next that is <= arr[i], so we pop while top > arr[i]. If equal, we don't pop so that we include equal on right? Actually we want right to be the first index with value < arr[i] or <=? For our rule: we want left: strictly less, right: less or equal. So for right, we pop while arr[stack[-1]] >= arr[i]? Wait:
# We want right[i] to be the first index to the right where arr[index] < arr[i]? Or <=?
# Let's derive: If we use left: prev strictly less, and right: next less or equal, then for duplicates, the leftmost one will get the subarrays that end before the next equal. That ensures each subarray's minimum is assigned to the leftmost occurrence of the minimum? Actually we need to avoid double counting. Consider arr = [1,1]. Subarrays: [0] min=1, [1] min=1, [0,1] min=1. We want to count each subarray once. If for i=0: left=-1, right=1 (since arr[1] =1 which is equal, so we want right to be index where arr <=? If we set right to the first index where arr < arr[i], then for i=0, right would be n (2) because no element less than 1. Then count = (0-(-1))(2-0)=12=2, contribution=12=2. For i=1: left=-1? Actually left for i=1: we pop while arr[stack[-1]] >= arr[1]? If we use strict < for left, then for i=1, the previous element arr[0]=1 is not < 1, so left[1] = -1? That gives (1-(-1))(2-1)=21=2, total 4, which is too much (should be 3). So we need to handle duplicates. Typically for sum of minimums, we use either:
# Option A: left: previous less (strictly), right: next less or equal.
# Option B: left: previous less or equal, right: next less (strictly).
# Both give correct sum. Let's test with [1,1]:
# Option A:
# For i=0: left=-1, right=1 (since arr[1]=1 <= arr[0] so we set right[0]=1). Count = (0-(-1))(1-0)=11=1.
# For i=1: left: we find previous less? There is none because arr[0]=1 not less, so left=-1. right: next less or equal? none, so right=2. Count = (1-(-1))(2-1)=2*1=2. Total=3. Good.
# So we want for right: next index where arr[index] <= arr[i]. So while stack and arr[stack[-1]] > arr[i], we pop? Actually we are traversing from right to left. We want right[i] to be the first index j>i such that arr[j] < arr[i]? No, we want <=. So we should pop while arr[stack[-1]] >= arr[i]? Because we want to find the first that is strictly less? Wait careful:
# We are building right boundaries: for each i, we want the smallest j>i such that arr[j] < arr[i]? Or <=? According to Option A: we want right[i] = first index j>i with arr[j] <= arr[i]. That means if arr[j] == arr[i], that j is a candidate for right. So we want to stop at an element that is less than or equal to arr[i]. So when scanning from right, we maintain a stack of indices with increasing values? Actually typical monotonic stack for "next smaller element" (strictly smaller) uses condition while stack and arr[stack[-1]] > arr[i] then pop. But if we want next smaller or equal, we use while stack and arr[stack[-1]] >= arr[i] then pop. Because then the top of stack after popping will be the next element that is < arr[i]? Let's think: We traverse from rightmost to left. We want for each i, right[i] = the smallest j>i such that arr[j] <= arr[i]. That is the next element that is less than or equal. So we want to maintain a stack that is increasing? Actually for next smaller element (strictly smaller), we pop while arr[stack[-1]] >= arr[i]? No, that's for next smaller or equal? Let's recall: To find next smaller element (strictly smaller), we do:
while stack and arr[stack[-1]] > arr[i]:
stack.pop()
right[i] = stack[-1] if stack else n
stack.append(i)
This gives next element that is smaller (strictly) because we pop all that are greater, so the top is smaller or equal? Actually if we pop while >, then we leave elements that are <=. So the top might be equal. That would give next element that is <=? Let's test: arr = [1,1]. For i=1 (rightmost), stack empty, right[1]=n, push 1. For i=0: while stack and arr[stack[-1]] > arr[0]? arr[1]=1, arr[0]=1, not >, so we don't pop. So right[0] = stack[-1] = 1. That gives right[0]=1, which is an index with equal value. That is what we want for Option A? In Option A we want right[i] to be the first index with arr[j] <= arr[i]. That includes equal. So we want to stop at equal. So the condition should be while stack and arr[stack[-1]] >= arr[i]? If we use >=, then for i=0, we see stack[-1]=1 with arr[1]=1 >= arr[0]=1, so we pop stack, then stack empty, so right[0]=n. That would be wrong for Option A. So for Option A (left: strictly less, right: less or equal), we need to compute right using condition while stack and arr[stack[-1]] > arr[i] (strictly greater) so that we keep equal on stack. That gives right[i] as the next index with value <= arr[i] (since we stop at equal or smaller). Actually if we pop only when strictly greater, then an equal value remains on stack, so the top will be the next element that is <= arr[i] (could be equal). That matches Option A: right[i] is the first index to the right with value <= arr[i]. Yes.
# For left: we want previous strictly less. When scanning left to right, we want left[i] = previous index with arr[j] < arr[i]. So we pop while arr[stack[-1]] >= arr[i]? Because if we pop when >=, then we remove elements that are equal or greater, leaving only strictly less. That gives left[i] = index of previous element that is strictly less. So for left, we use while stack and arr[stack[-1]] >= arr[i]: pop. Then left[i] = stack[-1] if stack else -1.
# So summary:
# left: pop while arr[stack[-1]] >= arr[i]
# right: pop while arr[stack[-1]] > arr[i]
# Then contribution = arr[i] * (i - left[i]) * (right[i] - i)
#
# Let's test with [1,1]:
# left: i=0: stack empty, left[0]=-1, push 0.
# i=1: while stack and arr[0] >= arr[1]? 1>=1 true, so pop, then stack empty, left[1]=-1, push 1.
# right: traverse from right.
# i=1: stack empty, right[1]=n, push 1.
# i=0: while stack and arr[stack[-1]] > arr[0]? arr[1]=1 > 1? false, so don't pop. right[0]=stack[-1]=1.
# Then contributions:
# i=0: arr[0]=1, (0-(-1))=1, (1-0)=1 => 1*1*1=1
# i=1: arr[1]=1, (1-(-1))=2, (2-1)=1 => 1*2*1=2
# sum=3 correct.
#
# Test with [2,1,2]:
# arr = [2,1,2]
# Expected sum of min of all subarrays:
# Subarrays: [0]:2, [0,1]:1, [0,1,2]:1, [1]:1, [1,2]:1, [2]:2 -> sum=2+1+1+1+1+2=8.
# Compute:
# left:
# i=0: left=-1, stack=[0]
# i=1: arr[stack[-1]]=2 >=1? yes, pop -> stack empty, left[1]=-1, push1.
# i=2: arr[stack[-1]]=1 >=2? no, so left[2]=1, push2.
# left = [-1,-1,1]
# right:
# i=2: stack empty, right[2]=3, push2.
# i=1: while stack and arr[2]=2 > arr[1]=1? yes, pop -> stack empty, right[1]=3, push1.
# i=0: while stack and arr[1]=1 > arr[0]=2? false, so right[0]=1, push0.
# right = [1,3,3]
# Contributions:
# i=0: 2 * (0-(-1)=1) * (1-0=1) = 2*1*1=2
# i=1: 1 * (1-(-1)=2) * (3-1=2) = 1*2*2=4
# i=2: 2 * (2-1=1) * (3-2=1) = 2*1*1=2
# sum=8 correct.
#
# So it works.
#
# So we'll implement sum_of_subarray_mins(arr) with that.
pass
Actually, we can compute left and right in two passes.
But note: we need to be careful about large numbers? The count might be large, but Python int handles.
Also, if there are zeros in heights, that's fine because arr[i] can be 0. Then contribution from a zero element will be zero. But note: if arr[i]=0, then it can be the minimum for subarrays that include it, but contribution is zero so it doesn't add to total. That's correct because if there is a column with zero height, then any subarray that includes that column will have min=0, meaning no rectangle (since height 0 means no vertical extent). But wait: if min=0, that means the rectangle would have height 0? Actually, in our interpretation, the number of rectangles for that column interval is min_height. If min_height=0, then there are 0 rectangles. So indeed we don't count anything from subarrays that have min=0. So it's fine.
But what about subarrays that have min>0? They contribute min. So the formula works.
Thus, we can implement.
Now, let's code sum_of_subarray_mins:
def sum_of_subarray_mins(arr):
n = len(arr)
left = [-1] * n
stack = []
for i in range(n):
while stack and arr[stack[-1]] >= arr[i]:
stack.pop()
left[i] = stack[-1] if stack else -1
stack.append(i)
right = [n] * n
stack = []
for i in range(n-1, -1, -1):
while stack and arr[stack[-1]] > arr[i]:
stack.pop()
right[i] = stack[-1] if stack else n
stack.append(i)
total = 0
for i in range(n):
total += arr[i] * (i - left[i]) * (right[i] - i)
return total
But careful: The product (i-left[i])*(right[i]-i) can be large, but Python int fine.
Now, we integrate.
But wait: There is a nuance: In our sum_of_subarray_mins, we are summing min over all subarrays. But in our context, for a fixed bottom row i, the number of rectangles with bottom row i is exactly sum_{all subarrays} min(arr). That is correct as argued.
But is there any issue with the fact that arr values are heights? For a subarray [l, r], the number of rectangles with bottom row i and columns l..r is min(arr[l..r]). That counts all possible top rows. But does it also count rectangles that have bottom row i but top row above i? Yes, because min gives the maximum possible height. But wait: For a given width [l,r], if the minimum height is H, then we can choose any top row from i-H+1 to i, giving H distinct rectangles. But are all these rectangles valid? For a given top row t, we need that for every column in [l,r], the height from t to i is at least (i-t+1). But since min height is H, for each column, the height is at least H. So if we choose t such that i-t+1 <= H, then for each column, the height is at least H >= i-t+1, so the segment from t to i is all ones. So yes, all H choices are valid. So number is H. So sum of min over all intervals gives total number of rectangles with bottom row i.
But is there any rectangle that is counted multiple times? For a given rectangle, its bottom row is fixed. So it is counted only when we process that bottom row. So no double counting.
Thus, total sum over all rows gives total rectangles.
Now, what about the initial example? We got 10.
Let's test with a simple all-ones grid:
grid = [[1,1],[1,1]]
h:
Row0: [1,1]
Row1: [2,2]
For row0: arr=[1,1]
Sum of min: subarrays: [0]:1, [0,1]:1, [1]:1 -> sum=3.
For row1: arr=[2,2]
Sum of min: subarrays: [0]:2, [0,1]:2, [1]:2 -> sum=6.
Total=9.
List all rectangles:
1x1: 4
1x2: 2 (two rows? Actually 1x2 rectangles: row0 cols0-1, row1 cols0-1 -> 2)
2x1: 2 (col0 rows0-1, col1 rows0-1 -> 2)
2x2: 1
Total = 4+2+2+1=9. Correct.
So algorithm works.
Now, what about the case where there are zeros? Already tested.
Thus, we have an O(m*n) solution.
But note: The stack method for sum of subarray minimums is O(n) per row, so total O(m*n). That is efficient even for large grids (like 1000x1000 -> 1e6 operations).
But wait: In the sum_of_subarray_mins, we are doing two passes with stack, each O(n). So yes.
Now, we need to write the function.
But what about the possibility that the grid might have integers other than 0 and 1? The problem says "grid of integers", but we only care about 1s. So we treat any non-zero? Actually it says "rectangles of 1s", so likely the grid contains 0s and 1s. But if there are other integers, we should treat only cells equal to 1 as ones? Probably. So we'll check grid[i][j] == 1.
But what if there are negative numbers? That doesn't make sense. So we assume binary.
Now, let's write the code.
We'll define:
def count_rectangles(grid):
if not grid or not grid[0]:
return 0
m, n = len(grid), len(grid[0])
heights = [0] * n
total = 0
for i in range(m):
for j in range(n):
if grid[i][j] == 1:
heights[j] += 1
else:
heights[j] = 0
total += sum_of_subarray_mins(heights)
return total
def sum_of_subarray_mins(arr):
n = len(arr)
left = [-1] * n
stack = []
for i in range(n):
while stack and arr[stack[-1]] >= arr[i]:
stack.pop()
left[i] = stack[-1] if stack else -1
stack.append(i)
right = [n] * n
stack = []
for i in range(n-1, -1, -1):
while stack and arr[stack[-1]] > arr[i]:
stack.pop()
right[i] = stack[-1] if stack else n
stack.append(i)
total = 0
for i in range(n):
total += arr[i] * (i - left[i]) * (right[i] - i)
return total
But wait: In the right pass, we used condition arr[stack[-1]] > arr[i]. That's for next less or equal? Actually we want right[i] to be the first index j>i such that arr[j] <= arr[i]. That means we should pop while arr[stack[-1]] >= arr[i]? Let's double-check with the example [1,1] we did earlier. We used while arr[stack[-1]] > arr[i] and got right[0]=1, which is correct for Option A. But in that example, arr[1]=1, arr[0]=1, so arr[stack[-1]] > arr[0]? 1>1 false, so we didn't pop. That gave right[0]=1. That means we are taking the next element that is <= (since equal is not >, we keep it). So the condition > means we pop only if strictly greater, leaving equal as candidate. So that gives next index with value <=? Actually if there is an equal, we don't pop it, so it becomes the right boundary. That means right[i] is the first index with value <= arr[i]? Not exactly: if the next element is equal, we stop at it, so right[i] points to that equal element. That is indeed the first index with value <= arr[i] because equal qualifies. If the next element is less, we would also stop? Let's see: if arr[i]=2 and next element arr[i+1]=1, then when processing i from right, for i, stack might have i+1 with value 1. Then condition arr[stack[-1]] > arr[i]? 1>2 false, so we don't pop, so right[i] = i+1. That is correct: first index with value <= 2 is i+1 (since 1<=2). So the condition > ensures we only pop elements that are greater, so the stack will have elements that are <= current. So after popping all greater, the top is the first element to the right that is <= current. So yes, that gives right[i] as the first index j>i with arr[j] <= arr[i]. Good.
For left, we used while arr[stack[-1]] >= arr[i] to pop. That means we pop elements that are greater or equal, so after popping, the top is the first element to the left that is strictly less? Because if we pop equal, then we skip equal, so left[i] will be the previous index with value < arr[i] (or -1). That's what we want: left[i] = previous index with arr[j] < arr[i]. So that's consistent.
So the conditions are correct.
But we should test with a case where there are duplicates and non duplicates.
Test with arr = [3,1,2,4]:
Manually compute sum of min of all subarrays.
Subarrays:
[0]:3
[0,1]:1
[0,1,2]:1
[0,1,2,3]:1
[1]:1
[1,2]:1
[1,2,3]:1
[2]:2
[2,3]:2
[3]:4
Sum = 3+1+1+1+1+1+1+2+2+4 = 17.
Now compute with algorithm:
left:
i=0: stack empty, left[0]=-1, stack=[0]
i=1: while stack and arr[0]=3 >=1? yes pop, stack empty, left[1]=-1, stack=[1]
i=2: while stack and arr[1]=1 >=2? no, left[2]=1, stack=[1,2]
i=3: while stack and arr[2]=2 >=4? no, left[3]=2, stack=[1,2,3]
left = [-1,-1,1,2]
right:
i=3: stack empty, right[3]=4, stack=[3]
i=2: while stack and arr[3]=4 >2? yes pop? 4>2 true, so pop, stack empty, right[2]=4, stack=[2]
i=1: while stack and arr[2]=2 >1? true, pop, stack empty, right[1]=4, stack=[1]
i=0: while stack and arr[1]=1 >3? false, so right[0]=1, stack=[1,0]? Actually we push 0 after? Let's do step by step:
After i=3: stack=[3]
i=2: pop stack because arr[3]=4 >2, stack becomes empty, right[2]=4, push 2 -> stack=[2]
i=1: while stack and arr[2]=2 >1? true, pop, stack empty, right[1]=4, push 1 -> stack=[1]
i=0: while stack and arr[1]=1 >3? false, so right[0]=1, push 0 -> stack=[1,0]
So right = [1,4,4,4]
Now contributions:
i=0: 3*(0-(-1)=1)(1-0=1)=3
i=1: 1(1-(-1)=2)(4-1=3)=123=6
i=2: 2(2-1=1)(4-2=2)=212=4
i=3: 4(3-2=1)(4-3=1)=41*1=4
Sum=3+6+4+4=17. Correct.
So algorithm works.
Now, we need to be careful about the fact that we are using the same array heights for each row. We update it in place.
But what if the grid is large? The heights array can have large values, but that's fine.
Now, what about time complexity? For each row we do O(n) for updating heights and O(n) for sum_of_subarray_mins. So total O(m*n). That's good.
But wait: There is a catch: The sum_of_subarray_mins as implemented uses two stacks and arrays left/right of size n. That is O(n) extra space per row, but we can reuse the same arrays if we want, but since we call it for each row, we are allocating new arrays each time. That is O(n) per row, total O(m*n) extra space if we keep all? But we don't keep; we deallocate after each call. So peak extra space is O(n) for the two arrays left and right and stacks. So overall O(n) extra space (plus the heights array). So O(n) extra space.
But we can also compute sum_of_subarray_mins without storing left and right arrays by computing contribution on the fly? Possibly, but it's fine.
Now, what about the possibility that the grid has more than 0 and 1? We only add to heights if grid[i][j]==1, else set to 0. So if there is a number like 2, we treat as not 1? The problem says "rectangles of 1s", so likely only 1 counts. So we should compare to 1.
But what if the grid contains only 0s and 1s? That's typical.
Now, let's think about an alternative interpretation: rectangles with all four corners as 1. That problem is different. How would we solve that? For each pair of rows (top and bottom), we can find columns where both rows have 1. Then for those columns, the number of rectangles is C(k,2) where k is the number of such columns. And we sum over all pairs of rows. That would be O(m^2 n) or O(m n) with bitwise operations if we use bitsets. But the problem says "rectangles of 1s", not "rectangles with corners as 1s". Usually "rectangles of 1s" means the entire rectangle is 1s.
Given the example we computed manually, it matches the all-ones submatrices count.
I'll provide explanation accordingly.
Now, we need to write the function and explain.
But let's consider another test: grid = [[1]] -> count=1. Our algorithm: row0 heights=[1], sum_of_subarray_mins([1]) = 1. Correct.
grid = [[0]] -> 0.
grid = [[1,1,1]] -> row0 heights=[1,1,1]. Sum of min for [1,1,1]: all subarrays: there are 6 subarrays? Actually for length 3, number of subarrays = 3*(3+1)/2 =6. min of each: all 1s so sum=6. That counts: 1x1:3, 1x2:2, 1x3:1 -> total 6. Correct.
grid = [[1],[1]] -> column vector. row0 heights=[1] -> sum=1. row1 heights=[2] -> sum=2. total=3. Rectangles: (0,0), (1,0), and (0,0)-(1,0) -> 3. Correct.
Now, what about grid with a single row and multiple columns? Already.
So it's consistent.
Now, I'll write the code accordingly.
But note: In the sum_of_subarray_mins function, we need to handle the case where n=0. But we call it only if n>0, since we have at least one column. But if grid has 0 columns? We already check grid[0] so n>=1.
But what if grid is empty? We return 0.
Now, we need to output the function.
But wait: There is a potential integer overflow? Not in Python.
Now, we should also consider that the grid might be given as list of lists of integers, but they might be strings? Probably not.
I'll write the function as:
def count_rectangles(grid):
"""
Count the number of axis-aligned submatrices that consist entirely of 1s.
"""
if not grid or not grid[0]:
return 0
m, n = len(grid), len(grid[0])
heights = [0] * n
total = 0
for i in range(m):
for j in range(n):
if grid[i][j] == 1:
heights[j] += 1
else:
heights[j] = 0
total += sum_of_subarray_mins(heights)
return total
def sum_of_subarray_mins(arr):
n = len(arr)
if n == 0:
return 0
left = [-1] * n
stack = []
for i in range(n):
while stack and arr[stack[-1]] >= arr[i]:
stack.pop()
left[i] = stack[-1] if stack else -1
stack.append(i)
right = [n] * n
stack = []
for i in range(n-1, -1, -1):
while stack and arr[stack[-1]] > arr[i]:
stack.pop()
right[i] = stack[-1] if stack else n
stack.append(i)
total = 0
for i in range(n):
total += arr[i] * (i - left[i]) * (right[i] - i)
return total
But we can also combine the two stacks into one function without arrays? But it's fine.
Now, explanation:
We use dynamic programming: for each cell, compute the number of consecutive ones vertically above (including current) -> heights. Then for each row, the number of all-ones submatrices ending at that row is the sum over all column intervals of the minimum height in that interval. That sum can be computed efficiently using the "sum of minimums of all subarrays" algorithm, which uses a monotonic stack to find for each element the number of subarrays where it is the minimum. The total over all rows gives the answer.
Complexity: O(m*n) time and O(n) extra space.
But wait: Is the sum of min of all subarrays algorithm O(n)? Yes, with two passes.
So overall O(m*n).
Now, what about the case where grid has many rows and columns? That's efficient.
But there is a nuance: The sum of min of all subarrays algorithm as described gives the sum of minimums. But we are using it directly as the count of rectangles. That is valid because for each interval, the number of rectangles is exactly the min height. So sum of min over all intervals equals total rectangles ending at that row.
But is there any rectangle that spans multiple rows and columns? Yes, they are counted when we process the bottom row of that rectangle. So it's correct.
Now, I think this is a solid solution.
But let's double-check with a more complex example to be sure.
Example:
grid = [
[1,1,0],
[1,1,1],
[0,1,1]
]
Let's compute manually:
All ones submatrices:
Row0: [1,1] -> two 1x1 and one 1x2? Actually row0: cells (0,0),(0,1) are 1. So rectangles: 1x1 at (0,0), (0,1); 1x2 at row0 cols0-1. That's 3.
Row1: cells: (1,0),(1,1),(1,2) all 1.
Rectangles with bottom row1:
- 1x1: three of them.
- 1x2: (1,0)-(1,1), (1,1)-(1,2) -> 2.
- 1x3: (1,0)-(1,2) -> 1.
- 2x1: from row0 to row1: columns where both rows have 1: col0 and col1. So two 2x1 rectangles.
- 2x2: rows0-1, cols0-1 -> that's all ones? Check: row0 cols0-1 are 1,1; row1 cols0-1 are 1,1 -> yes, so one 2x2.
- 2x3? rows0-1, cols0-2: row0 col2 is 0, so no.
So for bottom row1, total rectangles: 3 (1x1) + 2 (1x2) + 1 (1x3) + 2 (2x1) + 1 (2x2) = 9.
But wait, also 2x1 from row0-1 col2? No because row0 col2 is 0.
Also, what about 3x? Not yet because bottom row1 only.
So bottom row1 count = 9? But let's list all rectangles that have bottom row1 (i.e., bottom edge on row1). That includes all rectangles that end at row1. That means top row can be row1 or row0. And columns any. So we can compute via our method.
Now row2: cells: (2,1),(2,2) are 1.
Rectangles with bottom row2:
- 1x1: two.
- 1x2: (2,1)-(2,2) -> 1.
- 2x1: from row1 to row2: columns where both rows have 1: col1 and col2? Check: row1 col1=1, row1 col2=1, row2 col1=1, row2 col2=1. So col1 and col2 have 1 in both rows. So two 2x1 rectangles.
- 2x2: rows1-2, cols1-2: all ones? row1 cols1-2: [1,1], row2 cols1-2: [1,1] -> yes, so one 2x2.
- 3x1: from row0 to row2: columns where all three rows have 1? Only col1? Check: row0 col1=1, row1 col1=1, row2 col1=1 -> yes. So one 3x1 rectangle.
- 3x2: rows0-2, cols1-2: row0 col2=0, so no.
So bottom row2 count: 2 (1x1) + 1 (1x2) + 2 (2x1) + 1 (2x2) + 1 (3x1) = 7.
Also, what about 3x? only 3x1.
So total rectangles: row0:3, row1:9, row2:7 -> total 19.
Now let's compute with our algorithm.
First compute h:
Row0: [1,1,0]
Row1: [2,2,1] (since grid[1][2]=1, above was 0 so 1)
Row2: [0,3,2] (grid[2][0]=0, grid[2][1]=1 -> above was 2 so 3, grid[2][2]=1 -> above was1 so 2)
Now for each row:
Row0: arr=[1,1,0]
Sum of min of all subarrays:
Indices:0:1,1:1,2:0.
Subarrays:
[0]:1
[0,1]:1 (min of 1,1)
[0,1,2]:0
[1]:1
[1,2]:0
[2]:0
Sum = 1+1+0+1+0+0 = 3. Matches row0 count.
Row1: arr=[2,2,1]
Compute sum of min:
We can compute manually: all subarrays:
[0]:2
[0,1]:2 (min of 2,2)
[0,1,2]:1 (min of 2,2,1)
[1]:2
[1,2]:1
[2]:1
Sum = 2+2+1+2+1+1 = 9. Matches row1 count.
Row2: arr=[0,3,2]
Subarrays:
[0]:0
[0,1]:0
[0,1,2]:0
[1]:3
[1,2]:2 (min of 3,2)
[2]:2
Sum = 0+0+0+3+2+2 = 7. Matches row2 count.
Total=19. Good.
So algorithm works.
Now, we should consider if there is any rectangle that is not counted? For example, a rectangle that does not have its bottom row as the last row of the rectangle? That would be counted when we process that bottom row. So all are covered.
Thus, solution is correct.
Now, we need to write the function and explanation.
But wait: The problem statement says "Write a function to find the number of 'rectangles' of 1s." It might be that they want the number of rectangles (submatrices) that are composed entirely of 1s. That's what we did.
Now, we should provide the code in a clear manner.
But also, we might consider an alternative approach: For each cell as top-left corner, expand to right and down? That would be O(m^2 n^2). Not good.
So our solution is efficient.
Now, we need to output the final answer: the function.
But the user said "Please write a function that solves this problem, and explain your algorithm." So we need to provide both.
I'll provide the Python function and then explain step by step.
But before finalizing, let's consider if there is any edge case where the sum_of_subarray_mins might overflow or cause issues? For example, if heights are large, but Python handles big integers.
Also, note: The product (i-left[i])(right[i]-i) could be up to O(n^2) per element, but the sum over i is O(n^2) total? Actually the sum of (i-left)(right-i) over i is the number of subarrays, which is O(n^2). But we are not iterating over all subarrays; we are summing contributions from each element. That's fine.
Now, one more thing: The sum_of_subarray_mins function we wrote uses two arrays left and right of size n. That is O(n) space. For each row, we allocate new arrays. That's fine.
But we could optimize to not allocate arrays by computing contributions in one pass? Possibly with a stack that keeps track of contributions, but it's more complex. Not needed.
Now, I'll write the final answer.
But wait: There is a known Leetcode problem 1504, and many solutions use O(mn^2) by for each row, using a left array and then for each column, expanding leftwards. But our O(mn) is better.
But is O(m*n) always correct? Let's double-check the sum of min of all subarrays algorithm: It computes the sum of minimums, not the sum of the number of subarrays where each element is the minimum. That is exactly what we need. So yes.
But we must be careful: For a given row i, the number of rectangles with bottom row i is sum_{all intervals [l,r]} min(heights[l..r]). That is true. But is there any rectangle that is counted multiple times across rows? No, because each rectangle has a unique bottom row. So sum over rows gives total.
Thus, it's correct.
Now, we should also consider if the grid might have negative numbers? Only 1s matter.
Now, let's produce the answer.
But the user might expect the function name to be something like count_rectangles. I'll use that.
Now, I'll produce the final answer with code and explanation.
But wait: In the sum_of_subarray_mins, we used the condition for left: while stack and arr[stack[-1]] >= arr[i]. But what if arr[i] is 0? That's fine. But if there are multiple zeros, then left for a zero might be -1? Let's test arr=[0,0]:
left: i=0: left=-1, stack=[0]
i=1: while stack and arr[0]=0 >=0? yes, pop, stack empty, left[1]=-1, stack=[1]
right: i=1: right=2, stack=[1]
i=0: while stack and arr[1]=0 >0? false, so right[0]=1, stack=[1,0]
Contributions: i=0: 0*(0-(-1)=1)(1-0=1)=0; i=1: 0(1-(-1)=2)*(2-1=1)=0; sum=0. Correct because min for any subarray is 0, so no rectangles.
Now, what about arr with positive and zero? That's fine.
So code seems robust.
Now, one more thing: The sum_of_subarray_mins function might be called with arr that is the heights array. That array is updated each row. But after we call sum_of_subarray_mins, we go to next row and update heights. So we are not storing old heights. That's fine.
Now, let's implement in a clean way.
But I just realized: In the sum_of_subarray_mins, we are using the same array heights for each row. But heights is a list that we modify in place. When we call sum_of_subarray_mins(heights), it passes a reference. Inside sum_of_subarray_mins we read arr but don't modify it. That's fine.
Now, what about performance? For each row we do two passes over n. That's fine.
Now, let's consider if we can do it without the extra function by inlining? But for clarity, separate function is fine.
Now, we should provide an explanation.
Explanation:
We want to count all axis-aligned submatrices that contain only 1s.
Idea: For each cell, compute the number of consecutive 1s above it (including itself). Call this height[i][j]. This can be computed row by row.
For a fixed bottom row i, any rectangle ending at row i is defined by a column interval [l, r] and a top row t such that t <= i and for all columns in [l,r], the height from t to i is at least (i-t+1). The maximum possible height for that interval is min_{k in [l,r]} height[i][k]. For a given interval [l,r], the number of valid top rows is exactly that minimum (since we can choose any top row from i-min+1 to i). Therefore, the number of rectangles with bottom row i and column interval [l,r] is min(height[i][l..r]).
Thus, the total number of rectangles with bottom row i is the sum of minimums over all contiguous subarrays of the array height[i].
So we need to compute for each row i, the sum of minimums of all subarrays of the array h = height[i]. Summing over all rows gives the total number of rectangles.
The sum of minimums of all subarrays of an array can be computed in linear time using a monotonic stack. For each element arr[j], we find the number of subarrays where it is the minimum. This is (j - left) * (right - j), where left is the index of the previous element strictly less than arr[j] (or -1 if none) and right is the index of the next element less than or equal to arr[j] (or n if none). Then arr[j] contributes arr[j] * (j-left)*(right-j) to the sum.
We compute left and right arrays in two passes with a stack.
Overall algorithm runs in O(m*n) time and O(n) extra space.
Now, we'll code accordingly.
But wait: There is a nuance: In the sum of minimums, we use the rule that left is previous strictly less, right is next less or equal. That ensures each subarray's minimum is counted exactly once. The derivation is standard.
Now, let's write the final answer.
But before finalizing, let's test with a bigger random example to be sure? We can do a small test.
Test with grid:
[[1,0,1,1],
[1,1,1,1],
[0,1,1,0]]
Compute manually? Might be time-consuming but we can try.
Compute h:
Row0: [1,0,1,1]
Row1: [2,1,2,2] (since row1 col0:1 -> 2, col1:1 -> 1 (since row0 col1=0), col2:1 -> 2, col3:1 -> 2)
Row2: [0,2,3,0] (col0:0, col1:1 -> above 1 so 2, col2:1 -> above 2 so 3, col3:0)
Row0: arr=[1,0,1,1] -> sum of min:
Subarrays: total subarrays = 10. Let's compute quickly:
Indices:0:1,1:0,2:1,3:1.
All subarrays and min:
[0]:1
[0,1]:0
[0,1,2]:0
[0,1,2,3]:0
[1]:0
[1,2]:0
[1,2,3]:0
[2]:1
[2,3]:1
[3]:1
Sum = 1+0+0+0+0+0+0+1+1+1 = 4.
But wait, that seems low. Let's list all subarrays of length 4: there are 4*(4+1)/2=10. We have:
[0] ->1
[0,1] ->0
[0,1,2] ->0
[0,1,2,3] ->0
[1] ->0
[1,2] ->0
[1,2,3] ->0
[2] ->1
[2,3] ->1
[3] ->1
So sum=1+1+1+1=4. But what rectangles have bottom row0? They should be: 1x1 at (0,0), (0,2), (0,3) -> 3? Actually also 1x2 at row0, cols2-3? That's a rectangle of two cells. But in our sum for row0, we got only 4, but we have 3 single cells and 1 double? That totals 4. Yes, because we have (0,0), (0,2), (0,3), and (0,2)-(0,3). So 4. Correct. But what about (0,0)-(0,1)? That includes a 0 so not counted. So row0 count=4.
Row1: arr=[2,1,2,2]
Compute sum of min:
We can compute using formula. Let's do manually to verify.
All subarrays (10):
[0]:2
[0,1]:1 (min of 2,1)
[0,1,2]:1
[0,1,2,3]:1
[1]:1
[1,2]:1
[1,2,3]:1
[2]:2
[2,3]:2
[3]:2
Sum = 2+1+1+1+1+1+1+2+2+2 = 14? Let's add: 2+1=3, +1=4, +1=5, +1=6, +1=7, +1=8, +2=10, +2=12, +2=14. So 14.
But let's list rectangles with bottom row1:
1x1: all four cells? Actually row1 has all 1s so 4.
1x2: (1,0)-(1,1), (1,1)-(1,2), (1,2)-(1,3) -> 3.
1x3: (1,0)-(1,2), (1,1)-(1,3) -> 2.
1x4: (1,0)-(1,3) -> 1.
2x1: columns where row0 and row1 both 1: col0 (row0 col0=1), col2? row0 col2=1, col3=1? row0 col3=1. So col0, col2, col3. That's 3.
2x2: possible: cols0-1? row0 col1=0 so no. cols1-2? row0 col1=0 so no. cols2-3? row0 col2=1, row0 col3=1, row1 col2=1, row1 col3=1 -> yes. So one 2x2.
2x3: cols0-2? row0 col1=0 so no. cols1-3? row0 col1=0 so no.
2x4: no.
3x? bottom row1 only, so top row can be row0 or row1. So we already counted all with height 1 and 2. Did we miss any 2x1? We have 3. And 2x2 we have 1.
So total: 1x1:4, 1x2:3, 1x3:2, 1x4:1, 2x1:3, 2x2:1. Sum = 4+3+2+1+3+1 = 14. Correct.
Row2: arr=[0,2,3,0]
Sum of min:
Subarrays:
[0]:0
[0,1]:0
[0,1,2]:0
[0,1,2,3]:0
[1]:2
[1,2]:2 (min of 2,3)
[1,2,3]:0 (since 0 at end)
[2]:3
[2,3]:0
[3]:0
Sum = 0+0+0+0+2+2+0+3+0+0 = 7.
Now list rectangles with bottom row2:
Cells: (2,1)=1, (2,2)=1.
1x1: two.
1x2: (2,1)-(2,2) -> 1.
2x1: from row1 to row2: columns where both rows have 1: col1? row1 col1=1, row2 col1=1 -> yes; col2? row1 col2=1, row2 col2=1 -> yes. So two 2x1.
3x1: from row0 to row2: columns where all three rows have 1: col1? row0 col1=0, so no; col2? row0 col2=1, row1 col2=1, row2 col2=1 -> yes. So one 3x1.
2x2: rows1-2, cols1-2: row1 cols1-2: [1,1], row2 cols1-2: [1,1] -> yes, so one 2x2.
3x2: rows0-2, cols1-2: row0 col1=0, so no.
4x? no.
Also, what about 2x? we have 2x1 and 2x2. Also, what about 3x? we have 3x1.
So total: 1x1:2, 1x2:1, 2x1:2, 2x2:1, 3x1:1. Sum = 2+1+2+1+1=7. Correct.
Total overall: 4+14+7=25.
Now, if we compute all rectangles manually? That would be a lot but seems consistent.
So algorithm works.
Now, we need to write the function.
But wait: There is a possibility that the user might have meant "rectangles" as in geometric rectangles formed by 1s as corners? But our test with the first example gave 10, while if we count only corner-rectangles, what would we get? For the first example:
grid = [[1,0,1],[1,1,0],[0,1,1]]
Corners: we need to choose two distinct rows and two distinct columns such that all four corner cells are 1.
Rows: 0,1,2; columns:0,1,2.
Check all pairs:
Rows (0,1): columns where both rows have 1: row0: cols0,2; row1: cols0,1. Intersection: col0 only (since col0: row0=1, row1=1; col2: row0=1 but row1 col2=0; col1: row0=0, row1=1). So only col0. But we need at least two columns to form a rectangle. So none.
Rows (0,2): row0: cols0,2; row2: cols1,2. Intersection: col2 only. So none.
Rows (1,2): row1: cols0,1; row2: cols1,2. Intersection: col1 only. So none.
So no corner-rectangles. But our all-ones count is 10. So they are different.
Which one is more common? The problem statement: "rectangles of 1s". That could be interpreted as rectangles made of 1s, i.e., all cells inside are 1s. I think that's the intended meaning.
Also, if they meant corners, they might say "rectangles formed by 1s" meaning the 1s are the corners. But "rectangles of 1s" might be ambiguous.
Given the lack of further context, I'll assume all-ones submatrices.
But to be safe, we could mention both interpretations? The problem asks for a function, so we must choose one. I'll go with all-ones submatrices because it's a more interesting algorithmic problem and the corner-rectangle problem is simpler (O(m^2 n) or O(m n) with bitsets). Also, the sum-of-min trick is a nice algorithm.
However, the corner-rectangle problem can also be solved in O(m^2 n) or with optimization O(m n) if we precompute for each pair of rows the common columns using bitsets. But that's not as elegant.
Given that the user said "explain your algorithm", they likely expect a detailed explanation. The sum-of-min approach is a bit advanced but doable.
But wait: There is also an O(mn^2) approach for all-ones submatrices: for each row i, we can compute an array left_ones that counts consecutive ones to the left? Actually a common solution for Leetcode 1504 is O(mn^2) by for each row, we compute the number of consecutive ones to the right? Hmm.
But our O(m*n) is better.
I'll present the O(m*n) solution.
Now, let's write the final answer.
But I should also consider if the grid is given as a list of lists of integers, and we need to return an integer.
Now, one more thing: In the sum_of_subarray_mins function, we used the condition for left: while stack and arr[stack[-1]] >= arr[i]. But what about when arr[i] is 0? That's fine.
But I recall that for sum of minimums, the typical implementation uses:
for left: while stack and arr[stack[-1]] > arr[i]: pop (for next smaller element on left, we want previous less, so we pop while >=? Actually there are two variants.
Let's derive carefully:
We want for each i:
left[i] = the index of the previous element that is strictly less than arr[i].
right[i] = the index of the next element that is less than or equal to arr[i].
This is one valid choice.
When computing left from left to right:
We maintain a stack of indices with increasing values? Actually we want to find the previous less. So we can use a stack that keeps indices of elements that are potentially the previous less for future elements. We iterate i from 0 to n-1. For current arr[i], we pop from stack while the top element's value is >= arr[i] because those elements are not less than arr[i]; they are greater or equal, so they cannot be the previous less for any future element? Actually we are computing left[i]: we want the nearest j < i with arr[j] < arr[i]. So we need to keep in stack only elements that are strictly less than some upcoming? The standard method: while stack and arr[stack[-1]] >= arr[i]: pop. Then if stack non-empty, left[i] = stack[-1], else -1. Then push i. That ensures stack is increasing (strictly) from bottom to top? Actually after popping all >=, the top if exists is < arr[i]. So stack is monotonically increasing. That gives left[i] as previous less.
For right: we want the next index j>i with arr[j] <= arr[i]. We iterate from right to left. We maintain a stack. For current i, we pop while stack and arr[stack[-1]] > arr[i] (strictly greater) because we want to keep elements that are <= arr[i] as candidates for right boundary. If we pop while >, then after popping, the top if exists has arr[stack[-1]] <= arr[i]. That gives right[i] = stack[-1] if exists else n. Then push i. This makes the stack monotonically increasing from top to bottom? Actually from right to left, we are building a stack that is non-decreasing? But anyway it works.
I've tested with examples.
So I'll use that.
Now, let's code.
But we need to be cautious: In the right pass, we used while stack and arr[stack[-1]] > arr[i]. But in our earlier example with [2,1,2], we used that and got right[0]=1 because arr[1]=1 <=2? Actually arr[1]=1 which is <2, so it's <=. That's fine. But what if we have arr[i] and next element is equal? Then we want right[i] to point to that equal element? According to our rule, we want next index with value <= arr[i]. So if next is equal, that qualifies. So we should not pop when equal. So condition > is correct: we only pop if strictly greater. So if the top is equal, we stop and use it as right[i]. That gives right[i] = index of equal, which is correct for our rule.
Now, for left, we want previous strictly less, so we pop while >=, meaning we remove equal as well, so left[i] will not be an equal element. That ensures that for duplicates, the leftmost one will have left=-1, and the later ones will have left as the previous index that is strictly less (skipping equals). That is consistent with the assignment of minimum to the leftmost occurrence? Actually in our sum, we want each subarray's minimum to be counted exactly once. With left: prev strictly less, right: next less or equal, the minimum is assigned to the leftmost occurrence of the minimum value in the subarray. Because if there are duplicates, the leftmost one will have left boundary that is before any equal, and right boundary that is the next equal or less. That ensures that the subarray containing multiple equal minima is assigned to the leftmost one. That's fine.
So the conditions are correct.
Now, implement.
But note: In the right pass, we iterate from n-1 down to 0. We need to clear stack before.
Now, we should also handle the case where arr[i] might be very large, but that's fine.
Now, let's write the final code.
But wait: There is a potential bug: In sum_of_subarray_mins, we compute left and right arrays. But we might not need to store both if we compute contributions on the fly. But it's okay.
Now, what about the time complexity? For each row, we do O(n) for updating heights and O(n) for sum_of_subarray_mins. So total O(mn). That's optimal? Possibly could be O(mn) but with a constant factor. Good.
Now, we should provide an explanation that includes the concept of using heights and sum of minimums.
But before finalizing, let's consider if there is any rectangle that might be counted incorrectly when there are zeros in the heights? Already tested.
Now, what about a grid with a single column? Then for each row, arr is a single element. Sum_of_subarray_mins([h]) = h. So total = sum of heights. That equals number of rectangles? For a single column, the number of all-ones rectangles is the number of contiguous vertical segments of ones. That is indeed sum over each cell of the number of consecutive ones above including itself? Actually for a single column, the number of rectangles is the number of subarrays of consecutive ones in that column. That can be computed as sum_{each cell} (number of ones above including itself) because each cell contributes as the bottom of a rectangle: if at row i the height is h, then there are h rectangles ending at row i (from row i-h+1 to i). So total sum of h over i. That matches. So our method gives that.
So it's consistent.
Now, I think we are ready.
But one more thought: The problem might be from an interview where they expect the O(m^2 n) solution because it's simpler. But since we have an O(m*n) solution, it's better. However, we should explain it clearly.
Now, I'll write the answer.
In the explanation, I'll break down:
- Precompute vertical consecutive ones: heights[j] for each column j as we scan rows.
- For each row, the problem reduces to: given an array of heights, count sum of min over all subarrays. This is because for each subarray of columns, the number of rectangles with bottom row current and those columns is the minimum height in that subarray.
- To compute sum of minimums of all subarrays in O(n), use monotonic stack to find for each element the number of subarrays where it is the minimum.
- Sum contributions over all rows.
Now, code.
But wait: There is a known alternative: we can compute for each row, using a stack to compute the sum of minimums in a single pass? Actually we can compute sum of minimums in one pass with a stack that keeps track of increasing values and accumulates counts. That might be more efficient in practice. But our two-pass method is clear.
I'll stick with two-pass.
Now, let's write the final answer.
But I need to output the function. The user might want just the function, but also explanation.
So I'll provide:
def count_rectangles(grid):
"""
Count the number of axis-aligned submatrices that consist entirely of 1s.
"""
if not grid or not grid[0]:
return 0
m, n = len(grid), len(grid[0])
heights = [0] * n
total = 0
for i in range(m):
for j in range(n):
if grid[i][j] == 1:
heights[j] += 1
else:
heights[j] = 0
total += sum_of_subarray_mins(heights)
return total
def sum_of_subarray_mins(arr):
n = len(arr)
if n == 0:
return 0
left = [-1] * n
stack = []
for i in range(n):
while stack and arr[stack[-1]] >= arr[i]:
stack.pop()
left[i] = stack[-1] if stack else -1
stack.append(i)
right = [n] * n
stack = []
for i in range(n-1, -1, -1):
while stack and arr[stack[-1]] > arr[i]:
stack.pop()
right[i] = stack[-1] if stack else n
stack.append(i)
total = 0
for i in range(n):
total += arr[i] * (i - left[i]) * (right[i] - i)
return total
But we can also combine the two functions into one to avoid extra allocation? Not necessary.
Now, explanation:
Algorithm:
- We compute for each cell the number of consecutive 1s above it (including itself). This is stored in an array
heights as we iterate row by row.
- For a fixed bottom row, any all-ones rectangle ending at that row corresponds to a contiguous interval of columns [l, r]. The maximum possible height for that interval is the minimum of
heights[k] for k in [l, r]. The number of valid top rows is exactly that minimum. Therefore, the number of rectangles with bottom row at current row and column interval [l, r] is min(heights[l..r]).
- Thus, the total number of rectangles with bottom row at current row is the sum of minimums over all contiguous subarrays of
heights.
- We compute this sum efficiently using a monotonic stack. For each element
heights[j], we find the nearest previous element that is strictly less (left[j]) and the nearest next element that is less than or equal (right[j]). Then heights[j] is the minimum in exactly (j - left[j]) * (right[j] - j) subarrays. Summing heights[j] * count over all j gives the sum of minimums.
- We repeat for every row and accumulate the total.
Complexity: O(m*n) time and O(n) extra space.
Now, we should also mention that if the grid is large, this is efficient.
Now, I think that's it.
But wait: The user might expect the function name to be something else? Possibly count_rectangles or count_submatrices? I'll use count_rectangles as per problem.
Now, I'll provide the final answer.
We are counting the number of axis-aligned submatrices that consist entirely of 1s.
The solution uses dynamic programming and a monotonic stack to achieve O(m·n) time.
Algorithm
- Compute vertical heights: For each column
j, maintain heights[j] = number of consecutive 1s ending at the current row (including it). As we iterate row by row, update heights[j] (increment if grid[i][j]==1, else reset to 0).
- Interpretation for a fixed bottom row:
For the current row i (as bottom), any all‑1 rectangle with bottom row i is defined by:
- a contiguous column interval
[l, r],
- a top row
t such that all cells in rows t..i and columns l..r are 1.
For a given [l, r], the maximum possible height is H = min(heights[l..r]).
Any t with i - H + 1 ≤ t ≤ i works, giving exactly H distinct rectangles.
Hence, the number of rectangles with bottom row i and columns [l, r] is min(heights[l..r]).
- Sum over all intervals: For row
i, the total rectangles ending at i equals
Σ_{all subarrays [l,r]} min(heights[l..r]).
- Compute sum of minimums efficiently: For an array
arr, the sum of minimums of all its subarrays can be found in O(n) using a monotonic stack:
- For each index
j, find left[j] = index of the previous element strictly less than arr[j] (or -1 if none).
- Find
right[j] = index of the next element less than or equal to arr[j] (or n if none).
- Then
arr[j] is the minimum in exactly (j - left[j]) * (right[j] - j) subarrays.
- Contribution:
arr[j] * (j - left[j]) * (right[j] - j).
- Accumulate: Add the sum for the current row to the total. Repeat for all rows.
Complexity
- Time:
O(m·n) (each row processed in linear time).
- Space:
O(n) for the heights array and auxiliary stack/arrays.
Code
def count_rectangles(grid):
"""
Count the number of axis-aligned submatrices consisting entirely of 1s.
"""
if not grid or not grid[0]:
return 0
m, n = len(grid), len(grid[0])
heights = [0] * n
total = 0
for i in range(m):
for j in range(n):
if grid[i][j] == 1:
heights[j] += 1
else:
heights[j] = 0
total += sum_of_subarray_mins(heights)
return total
def sum_of_subarray_mins(arr):
"""Return sum of minimums of all contiguous subarrays of arr."""
n = len(arr)
if n == 0:
return 0
left = [-1] * n
stack = []
for i in range(n):
while stack and arr[stack[-1]] >= arr[i]:
stack.pop()
left[i] = stack[-1] if stack else -1
stack.append(i)
right = [n] * n
stack = []
for i in range(n - 1, -1, -1):
while stack and arr[stack[-1]] > arr[i]:
stack.pop()
right[i] = stack[-1] if stack else n
stack.append(i)
total = 0
for i in range(n):
total += arr[i] * (i - left[i]) * (right[i] - i)
return total
Example
For grid = [[1,0,1],[1,1,0],[0,1,1]] the function returns 10, matching the 10 all‑1 rectangles.