Open In App

Maximum size rectangle binary sub-matrix with all 1s

Last Updated : 23 Jul, 2025
Comments
Improve
Suggest changes
139 Likes
Like
Report

Given a 2d binary matrix mat[][], the task is to find the maximum size rectangle binary-sub-matrix with all 1's

Examples: 

Input:
mat = [
[0, 1, 1, 0],
[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 0, 0] ]

Output : 8
Explanation : The largest rectangle with only 1's is from (1, 0) to (2, 3) which is
[1, 1, 1, 1]
[1, 1, 1, 1]

Input:
mat = [
[0, 1, 1],
[1, 1, 1],
[0, 1, 1] ]

Output: 6
Explanation: The largest rectangle with only 1's is from (0, 1) to (2, 2) which is
[1, 1]
[1, 1]
[1, 1]

There is already an algorithm discussed a dynamic programming based solution for finding the largest square with 1s

Using Largest Rectangular Area in a Histogram Approach - O(n*m) Time and O(m) Space

This approach is based on Largest Rectangular Area in a Histogram.

  • Consider each row (starting from the top row) as the base of the histogram chart formed with all 1s.
  • For each row, increase height of a bar by the amount of the previous row, only if the value in current row is 1 and calculate the largest rectangular area of that histogram.
  • The largest rectangular area of a histogram among all possible base rows is the required are of the rectangle.

Illustration: 

Input :
0 1 1 0
1 1 1 1
1 1 1 1
1 1 0 0
Step 1:
0 1 1 0 maximum area = 2
Step 2: For the remaining rows, we add previous row only if the current cell's value is 1
row 1 1 2 2 1 area = 4, maximum area for this row becomes 4
row 2 2 3 3 2 area = 8, maximum area for this row becomes 8
row 3 3 4 0 0 area = 6, maximum area for this row remains 8

C++
Java Python C# JavaScript

Output
8

Using Dynamic Programming (Memoization) - O((n^2)*m) Time and O(n*m) Space

The idea is to store the width of consecutive 1's ending at each cell (i, j) in a 2D array. Starting from each cell (i, j) with value 1, iterate upwards row by row, find the minimum width of 1's in the column to ensure the rectangle remains valid. The area of the rectangle is then calculated as the minimum width multiplied by the height, updating the maximum area encountered so far.

  • Create a 2D matrix memo of size n*m, initialized to 0, to store the width of consecutive 1s ending at each cell (i, j).
  • Iterate through each cell (i, j) in the input matrix. If the value at (i, j) is 1, follow steps:
    • Set memo[i][j] = 1 if j == 0, otherwise set memo[i][j] = 1 + memo[i][j - 1].
    • Initialize width = memo[i][j].
    • For each row k from i to 0, update width = min(width, memo[k][j]) and calculate the rectangle area as width*(i - k + 1). Update the maximum area found so far.
  • Return the maximum area calculated.
C++
Java Python C# JavaScript

Output
8

Related articles:


Next Article

Similar Reads