Count Submatrices With All Ones - Problem

Given an m x n binary matrix mat, return the number of submatrices that have all ones.

A submatrix is a contiguous rectangular region within a matrix. For example, in a 3x3 matrix, there are many possible submatrices of different sizes and positions.

Example: If the matrix is [[1,1,0],[1,1,0],[0,0,1]], we need to count all rectangular regions that contain only 1s.

Input & Output

Example 1 — Basic Matrix
$ Input: mat = [[1,0,1],[1,1,0],[1,1,0]]
Output: 4
💡 Note: Valid submatrices are: [1] at (0,0), [1] at (0,2), [1] at (1,0), [1,1] at (1,0)-(1,1), [1] at (2,0), [1] at (2,1)
Example 2 — All Ones
$ Input: mat = [[1,1],[1,1]]
Output: 9
💡 Note: Four 1x1 submatrices, four 1x2 or 2x1 submatrices, and one 2x2 submatrix
Example 3 — All Zeros
$ Input: mat = [[0,0],[0,0]]
Output: 0
💡 Note: No submatrix contains all ones

Constraints

  • 1 ≤ m, n ≤ 150
  • mat[i][j] is either 0 or 1

Visualization

Tap to expand
Count Submatrices With All OnesInput Matrix:101110110Valid Submatrices:1x1 at (0,0)1x1 at (0,2)2x2 at (1,0)+ 2 more 1x1 rectanglesat (1,0), (2,0), (2,1)Output: 4 submatrices
Understanding the Visualization
1
Input Matrix
Binary matrix with 0s and 1s
2
Find Submatrices
Identify all rectangular regions with only 1s
3
Count Total
Return the total count of valid submatrices
Key Takeaway
🎯 Key Insight: Transform into histogram problem - count rectangles efficiently using heights and monotonic stack
Asked in
Amazon 15 Google 12
78.0K Views
Medium Frequency
~25 min Avg. Time
2.8K 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