Largest rectangle in a histogram

Stack / Queues FAQs Hard
  • This problem and its underlying concept are integral to numerous real-world applications including image processing, where you might need to find the largest rectangle in a histogram to optimize cropping strategies
  • Additionally, such problems are used in statistical data analysis, allowing developers to identify the most significant data ranges in large datasets
  • Furthermore, it is also an underlying concept for allocation of screen space in some User Interface (UI) design algorithms for maintaining proper layout and to provide better visual aesthetics

Given an array of integers heights representing the histogram's bar height where the width of each bar is 1 return the area of the largest rectangle in the histogram.

Examples:

Input: heights = [2, 1, 5, 6, 2, 3]

Output: 10


Explanation: The largest rectangle is highlighted, which has an area of 5*2 = 10 units.

Input: heights = [3, 5, 1, 7, 5, 9]


Output: 15


Explanation: The largest rectangle has an area of 5*3 = 15 units.

Input: heights = [2,4]

Constraints

  •   1 <= heights.length <= 105
  •   0 <= heights[i] <= 104

Hints

  • Using Monotonic Stack, Use a monotonic increasing stack to efficiently find the next smaller element on the left and right for each bar. Compute width using nearest smaller elements and calculate the max area.
  • Using Divide and Conquer Find the smallest bar, use it as a partition, and recursively compute the max rectangle in left and right segments.

Company Tags

AMD OYO Rooms Cloudflare Texas Instruments Freshworks Rockstar Games Philips Healthcare Epic Systems Swiggy Byju's NVIDIA Mastercard Zomato Intel Shopify Western Digital HashiCorp McKinsey & Company Teladoc Health Rakuten IBM Optum Ernst & Young Salesforce PwC Google Microsoft Amazon Meta Apple Netflix Adobe