Tutorialspoint
Problem
Solution
Submissions

Maximal Rectangle

Certification: Advanced Level Accuracy: 0% Submissions: 0 Points: 15

Write a C program to find the largest rectangle containing only 1's in a binary matrix. Given a rows x cols binary matrix filled with 0's and 1's, find the largest rectangle containing only 1's and return its area.

Example 1
  • Input: matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]]
  • Output: 6
  • Explanation:
    • The matrix has several rectangles of 1's.
    • The maximal rectangle is at positions forming a 2x3 rectangle.
    • This rectangle has area = 2 * 3 = 6.
    • Therefore, maximal rectangle area = 6.
Example 2
  • Input: matrix = [["0"]]
  • Output: 0
  • Explanation:
    • The matrix contains only one element which is "0".
    • No rectangle of 1's can be formed.
    • Therefore, maximal rectangle area = 0.
Constraints
  • rows == matrix.length
  • cols == matrix[i].length
  • 1 ≤ row, cols ≤ 200
  • matrix[i][j] is '0' or '1'
  • Time Complexity: O(rows * cols)
  • Space Complexity: O(cols)
MatrixDropboxD. E. Shaw
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use the concept of largest rectangle in histogram for each row
  • For each row, calculate heights of consecutive 1's ending at that row
  • Apply largest rectangle in histogram algorithm on these heights
  • Use stack-based approach to find maximum rectangle efficiently
  • Update heights array: if current cell is '0', height becomes 0, else increment

Steps to solve by this approach:

 Step 1: Initialize a heights array to track consecutive 1's ending at each column for current row.
 Step 2: For each row in the matrix, update the heights array based on current row values.
 Step 3: If current cell is '1', increment the corresponding height, otherwise reset height to 0.
 Step 4: Apply largest rectangle in histogram algorithm on the updated heights array.
 Step 5: Use stack-based approach to efficiently find maximum rectangle area in the histogram.
 Step 6: Keep track of maximum area found across all rows.
 Step 7: Return the maximum rectangle area found in the entire matrix.

Submitted Code :