L3 · FAANGIntervals & greedy~25 min · 6 tests

Largest Rectangle in a Histogram

Find the largest rectangle in a histogram in O(n) with a monotonic increasing stack that computes each bar's left and right limits. A tough FAANG classic.

The problem

heights are bar heights of width 1. Return the area of the largest rectangle that fits entirely under the histogram.

Examples

  1. Example 1

    Input

    largest_rectangle([2, 1, 5, 6, 2, 3])

    Expected output

    10
  2. Example 2

    Input

    largest_rectangle([2, 4])

    Expected output

    4

+ 4 hidden tests on Submit.

Edge cases to ask about

  • Increasing or decreasing heights
  • Zeros
  • Empty

Hints

0/3

    How an interviewer scores this

    0/9
    Python 3.13 · largest_rectangle
    ⌘/Ctrl + Enter runs the examples

    Your code runs in real CPython inside your browser — nothing is sent anywhere. The first run downloads the interpreter (about 6 MB, once). Your code is saved on this device as you type.

    Complexity Lab

    What does this cost as n grows?

    Interviewers score the analysis as much as the code. Commit to an answer first — then check it, and measure your code against the optimal one at growing input sizes.

    Time complexity of the optimal solution
    Space complexity (extra memory)

    Pick both to reveal the answer.

    Measure it

    Runs the function on inputs of size 250 up to 16,000 and records the time and peak memory. Slow solutions stop early — a short curve is itself the answer.

    From brute force to optimal

    The progression an interviewer wants to hear, one step at a time.

    ApproachTimeSpaceIdea
    Every (i, j) range with a running minimumO(n²)O(1)
    bestMonotonic increasing stackO(n)O(n)When a bar is popped, its left and right limits are both known.
    Walkthrough of the optimal approach (try it yourself first)

    For each bar, the best rectangle using its height extends left and right until it hits a shorter bar. A stack of indices with increasing heights finds both limits: when bar i is shorter than the top, the top's right limit is i and its left limit is whatever is below it on the stack.

    Appending a sentinel 0 flushes everything at the end. Each index is pushed and popped once — O(n).

    Complexity: O(n) time, O(n) space. Each index is pushed and popped once; the stack can hold n indices.

    Reveal the reference solution
    def largest_rectangle(heights):
        stack = []          # indices with increasing heights
        best = 0
        for i, h in enumerate(heights + [0]):
            while stack and heights[stack[-1]] >= h:
                height = heights[stack.pop()]
                left = stack[-1] + 1 if stack else 0
                best = max(best, height * (i - left))
            stack.append(i)
        return best

    The brute force, for comparison

    def largest_rectangle(heights):
        best = 0
        for i in range(len(heights)):
            low = heights[i]
            for j in range(i, len(heights)):
                low = min(low, heights[j])
                best = max(best, low * (j - i + 1))
        return best

    Follow-ups interviewers ask

    • Maximal rectangle of 1s in a binary matrix (this, row by row).

    Frequently asked interview questions

    Core interview concepts, complexities, and follow-ups scored by hiring teams.

    What is the time complexity of Largest Rectangle in a Histogram in Python?

    The optimal solution runs in O(n) time and O(n) auxiliary space. Each index is pushed and popped once; the stack can hold n indices.

    What is the brute-force approach, and how do you optimise it?

    Every (i, j) range with a running minimum: O(n²) time, O(1) space. Monotonic increasing stack: O(n) time, O(n) space. When a bar is popped, its left and right limits are both known.

    What follow-up questions do interviewers ask about Largest Rectangle in a Histogram?

    Maximal rectangle of 1s in a binary matrix (this, row by row).