Count Submatrices With All Ones - Problem

Given an m x n binary matrix mat containing only 0s and 1s, your task is to count the total number of submatrices that contain all ones.

A submatrix is any rectangular region within the original matrix. This includes single cells, entire rows, entire columns, and any rectangular combination in between.

Example: In a 2x2 matrix with all ones, there are 9 possible submatrices: 4 individual cells, 2 horizontal rectangles, 2 vertical rectangles, and 1 full matrix - all containing only ones!

๐ŸŽฏ Goal: Return the count of all such submatrices efficiently.

Input & Output

example_1.py โ€” Basic 3x3 Matrix
$ Input: mat = [[1,0,1],[1,1,0],[1,1,0]]
โ€บ Output: 13
๐Ÿ’ก Note: There are 13 submatrices with all ones: 6 of size 1x1, 4 of size 1x2, 2 of size 2x1, and 1 of size 2x2. The zeros break many potential larger rectangles.
example_2.py โ€” Small Square
$ Input: mat = [[1,1],[1,1]]
โ€บ Output: 9
๐Ÿ’ก Note: A 2x2 matrix of all ones contains: 4 submatrices of size 1x1, 2 of size 1x2, 2 of size 2x1, and 1 of size 2x2. Total = 4+2+2+1 = 9.
example_3.py โ€” Single Row
$ Input: mat = [[1,1,0,0]]
โ€บ Output: 4
๐Ÿ’ก Note: Only the first two consecutive 1s can form submatrices: two 1x1 submatrices, one 1x2 submatrix, plus the individual 1s again gives us 3 total submatrices containing all ones.

Visualization

Tap to expand
Original Matrix110111Height Matrix110221Histogram AnalysisRow 0: [1,1,0] โ†’ 3 rectanglesRow 1: [2,2,1] โ†’ 6 rectanglesUsing monotonic stack:โ€ข Count rectangles by heightโ€ข Use stack for efficiencyTotal: 9 rectangles
Understanding the Visualization
1
Build Heights
For each row, calculate height of consecutive 1s ending at each position
2
Create Histogram
Treat each row as a histogram with calculated heights
3
Count Rectangles
Use monotonic stack to count all rectangles in each histogram
4
Sum Results
Add up rectangle counts from all rows
Key Takeaway
๐ŸŽฏ Key Insight: Transform 2D matrix counting into 1D histogram problems - each row becomes a histogram where we count rectangles using monotonic stack technique!

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(mยฒnยฒ)

For each cell, we may expand to create O(mn) submatrices in worst case

n
2n
โš  Quadratic Growth
Space Complexity
O(1)

Only using constant extra space for variables

n
2n
โœ“ Linear Space

Constraints

  • 1 โ‰ค rows, cols โ‰ค 150
  • mat[i][j] is either 0 or 1
  • Matrix contains only binary values
  • Submatrix must be rectangular (not arbitrary shape)
Asked in
Google 45 Amazon 38 Meta 32 Microsoft 28 Apple 24
38.0K Views
Medium Frequency
~25 min Avg. Time
1.4K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen