Workspace

Problem workspace

3 day streakD

Largest Rectangle in a Histogram

HardStacksAreas & contributions

The challenge

Return the largest rectangular area beneath a histogram of unit-width bars.

Nonnegative integer heights. An empty histogram returns 0.

Example

[2,1,5,6,2,3] → 10.

Use the walkthrough below to inspect the input and each state change.

See Largest Rectangle in a Histogram, step by step

Inspect each push, pop, and recorded answer. Entries such as 2: 5 mean index: value.

Zero-based input · top labeled explicitlyLIFO
Input and stack stateCurrent input index: -1. Main stack bottom to top: []. Auxiliary stack · bottom → top: []. Read the input in order. The stack keeps only the state needed to resolve the next item.201152632435Main stack · bottom → top ↑emptyAuxiliary · bottom → top ↑empty
Current input index
—
Main stack size
0
Step 01 / 15

Start with an empty stack

Read the input in order. The stack keeps only the state needed to resolve the next item.

Answer so far

Not recorded yet
Main stack · bottom → top
Empty
Auxiliary stack · bottom → top
Empty
View exact input and state

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

Main stack: []. Auxiliary stack · bottom → top: [].

Put it into code

Pop a taller bar and measure width between its smaller boundaries.

Indices are zero-based. C++ uses C++17 or later.

def histogram(heights):
    stack, best = [], 0
    for i in range(len(heights) + 1):
        height = heights[i] if i < len(heights) else 0
        while stack and heights[stack[-1]] > height:
            j = stack.pop()
            left = stack[-1] if stack else -1
            best = max(best, heights[j] * (i - left - 1))
        if i < len(heights): stack.append(i)
    return best


def solve(heights):
    return histogram(heights)

A good place to start

Explore a pattern

A little guidance

Start with a pattern, read through a problem, and mark it solved when the idea clicks. Save anything you want to revisit.

New tutorials are added one at a time. Your bookmarks and solved checkmarks stay in this browser.

Explore the roadmap