The "Count Submatrices With All Ones interview question" is an extension of the "Count Square Submatrices" problem. You are given an binary matrix and need to count ALL possible rectangular submatrices that consist only of ones. This includes squares, single cells, and long thin rectangles.
Meta and Bloomberg ask the "Count Submatrices With All Ones coding problem" to test a candidate's ability to reduce a 2D problem into a series of 1D problems. It requires knowledge of either monotonic stacks or specialized histograms. It is a classic "Dynamic Programming" and "Stack interview pattern" challenge that evaluations spatial reasoning.
This problem follows the Histogram and Monotonic Stack pattern.
(i, j).height[i][j] = (matrix[i][j] == 1) ? height[i-1][j] + 1 : 0.(i, j) can be calculated using a monotonic stack. The stack maintains indices of increasing heights. The number of rectangles at is based on the height at and the "contributions" from smaller heights to its left.total_rects[j] = height[j] * (j - prev_smaller_idx) + total_rects[prev_smaller_idx].Matrix:
1 1
1 1
[1, 1]. Rectangles: [1, 2]. (Subarrays [1], [1], [1,1]). Sum = 3.[2, 2]. Rectangles: [2, 4]. (Subarrays of height 1: 3; Subarrays of height 2: 3). Sum = 6.
Total: 9.This problem is very similar to "Largest Rectangle in Histogram." If you master the monotonic stack for histograms, you can solve many "Hard" matrix problems. Always remember: "A matrix is just a stack of histograms."
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Maximal Rectangle | Hard | Solve | |
| Sum of Subarray Minimums | Medium | Solve | |
| Number of People That Can Be Seen in a Grid | Medium | Solve | |
| Maximum Number of Books You Can Take | Hard | Solve | |
| Minimum Cost Tree From Leaf Values | Medium | Solve |