Maximum Rectangles

Stack / Queues FAQs Hard
  • This programming problem is at the core of image processing tasks in fields such as computer vision and graphics
  • For instance, in object detection (like detecting faces in a social media photo tagging system), such algorithms can be used to locate the largest rectangular region containing the object of interest
  • Also, in digital print and scanning applications, the largest rectangle of 1's can be used to identify and remove noise or to center the focus on the desired object, improving image quality

Given a m x n binary matrix filled with 0's and 1's, find the largest rectangle containing only 1's and return its area.

Examples:

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 highlighted part depicts the rectangle with the largest area i.e. 6.

Input : matrix = [[1]] 

Output: 1 

Explanation: In this case, there is only one rectangle with area 1.

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

Constraints

  •   1<=n,m<=1000
  •   0<=matrix[i][j]<=1

Hints

  • Convert each row into a histogram For each row i, compute a heights array, where: heights[j]=heights[j]+1if matrix[i][j]=1, else 0 This transforms each row into a histogram where heights represent consecutive 1s.
  • Apply the Largest Rectangle in Histogram algorithm. Use monotonic stack to compute maximum rectangular area row-wise. Track the maximum area across all rows.

Company Tags

PwC Splunk KPMG OYO Rooms Byju's Dropbox Airbnb Databricks Epic Games Activision Blizzard NVIDIA Bain & Company GE Healthcare Etsy Reddit Ernst & Young Riot Games Chewy Roche IBM Electronic Arts Robinhood Uber Texas Instruments Walmart Google Microsoft Amazon Meta Apple Netflix Adobe