Tutorialspoint
Problem
Solution
Submissions

Maximal Rectangle

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

Write a C++ program to find the maximal rectangle in a binary matrix. Given a rows x cols binary matrix filled with 0's and 1's, find the area of 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 maximal rectangle is shown in the above grid.
    • It forms a 2x3 rectangle of all 1's, which has area = 6.
Example 2
  • Input: matrix = [["0"]]
  • Output: 0
  • Explanation:
    • There is no '1' in the matrix, so the max rectangle area is 0.
Constraints
  • rows == matrix.length
  • cols == matrix[i].length
  • 1 ≤ rows, cols ≤ 200
  • matrix[i][j] is '0' or '1'
  • Time Complexity: O(rows * cols)
  • Space Complexity: O(cols)
ArraysMicrosoftTCS (Tata Consultancy Services)
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

  • Convert the 2D problem into a series of 1D problems
  • For each row, compute the height of the '1's bar ending at that position
  • For each position in a row, calculate the largest rectangle using the "largest rectangle in histogram" approach
  • Use a stack to track heights in ascending order
  • When a height decreases, calculate areas of rectangles that can be formed

Steps to solve by this approach:

 Step 1: For each row in the matrix, build a histogram where the height at each position represents the number of consecutive '1's above (including the current position).
 Step 2: For each histogram, find the largest rectangle area using the "largest rectangle in histogram" algorithm.
 Step 3: Use a stack to keep track of bars in ascending order of height.
 Step 4: When encountering a bar shorter than the one at the top of the stack, calculate the area of rectangles that must end at the current position.
 Step 5: After processing all rows, return the maximum area found across all histograms.
 Step 6: For the histogram calculation, ensure proper handling of edge cases (empty stack, index calculations).
 Step 7: The final answer is the maximum rectangle area found among all rows.

Submitted Code :