> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Largest Rectangle in Histogram Python Solution

> Tested Python solution for LeetCode 84 with 16 pytest cases. Generate a practice environment with lcpy.

LeetCode 84, Hard. Topics: Array, Stack, Monotonic Stack. [View on LeetCode](https://leetcode.com/problems/largest-rectangle-in-histogram/description/).

Generate this problem as a practice environment: tested reference solution, 16 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 84   # by problem number
lcpy gen -s largest_rectangle_in_histogram   # by problem name
```

## Problem

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

![Example 1](https://assets.leetcode.com/uploads/2021/01/04/histogram.jpg)

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

**Explanation:** The above is a histogram where width of each bar is 1. The largest rectangle is shown in the red area, which has an area = 10 units.

![Example 2](https://assets.leetcode.com/uploads/2021/01/04/histogram-1.jpg)

```
Input: heights = [2,4]
Output: 4
```

### Constraints

* `1 <= heights.length <= 10^5`
* `0 <= heights[i] <= 10^4`

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/largest_rectangle_in_histogram/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/largest_rectangle_in_histogram/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class Solution:
    # Time: O(n)
    # Space: O(n)
    # Monotonic stack approach
    # Stack stores indices of bars in increasing height order
    # When we find a shorter bar, we calculate area using previous bars
    def largest_rectangle_area(self, heights: list[int]) -> int:
        stack: list[int] = []  # Stack of indices
        max_area = 0

        for i, height in enumerate(heights):
            # While current height is less than stack top height
            # Pop from stack and calculate area with popped height as smallest
            while stack and heights[stack[-1]] > height:
                max_area = max(max_area, self.calculate_area(heights, stack, i))

            stack.append(i)

        while stack:
            max_area = max(max_area, self.calculate_area(heights, stack, len(heights)))

        return max_area

    @staticmethod
    def calculate_area(heights: list[int], stack: list[int], right_bound: int) -> int:
        h = heights[stack.pop()]
        w = right_bound if not stack else right_bound - stack[-1] - 1
        return h * w
```

## Complexity

| Time | Space |
| ---- | ----- |
| O(n) | O(n)  |

## Tags

[Grind 75](/catalog/grind-75), [Grind](/catalog/grind), [NeetCode 150](/catalog/neetcode-150), [NeetCode 250](/catalog/neetcode-250), [NeetCode All](/catalog/neetcode), [AlgoMaster 75](/catalog/algo-master-75).
