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: 10
💡 Note: Valid submatrices with all ones: 7 single-cell [1] submatrices at positions (0,0), (0,2), (1,0), (1,1), (2,0), (2,1); 2 vertical 2×1 submatrices at columns 0 and 1; 1 horizontal 1×2 submatrix at row 1; and 1 full 2×2 submatrix in the bottom-left corner
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 Ones INPUT Binary Matrix (3x3) 1 0 1 1 1 0 1 1 0 = 1 (valid) = 0 (invalid) mat = [[1,0,1], [1,1,0], [1,1,0]] ALGORITHM (DP) 1 Count Consecutive 1s For each row, count consecutive 1s to left 2 Build Height Array Track width at each position going down 3 Enumerate Submatrices For each cell, extend upward counting valid 4 Sum All Counts Add up all valid submatrix counts Width Array (dp): 1 0 1 1 2 0 1 2 0 FINAL RESULT Valid Submatrices Found: 1x1 at (0,0) 1 1x1 at (0,2) 1 1x1 at (1,0) 1 1x1 at (1,1) 1 + more 1x1, 1x2, 2x1, 2x2... Counting all valid submatrices: 1x1: 6 cells with 1 1x2: 2 | 2x1: 2 | 2x2: 1 Total = 13 Output: 13 Key Insight: Use DP to precompute consecutive 1s to the left for each cell. Then for each cell (i,j), extend upward while tracking minimum width. Each extension adds min_width to total count. This avoids O(n^4) brute force, achieving O(m^2 * n) time complexity where m=rows, n=cols. TutorialsPoint - Count Submatrices With All Ones | Dynamic Programming Approach
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