Python coding

Largest rectangle under bars

heights describes a row of bars standing side by side, each 1 unit wide. Return the area of the largest rectangle that fits entirely under the bars. A rectangle may span several adjacent bars; its height is limited by the shortest bar it covers.

Aim for O(n): trying every pair of edges is O(n²).

Besides the tests, one large input (3,000 bars) with a ~200 ms limit (scaled to your device's speed): brute force won't pass.

  • largest_rectangle([2,1,5,6,2,3]) → 10
  • largest_rectangle([2,4]) → 4
  • largest_rectangle([3,3,3,3]) → 12
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

The best rectangle of a bar's height reaches left and right until the first shorter bar. A monotonic stack finds both limits.

Hint 2

Keep indexes with increasing heights. When a shorter bar arrives at i, pop the top: its right limit is i, its left limit is the new top + 1.

Hint 3

Bars left on the stack at the end still need an answer: append a bar of height 0 to flush them all.

Solution and why it works
pythonO(n) · O(n)
def largest_rectangle(heights: list[int]) -> int:
    best, stack = 0, []
    for i, h in enumerate(heights + [0]):
        while stack and heights[stack[-1]] >= h:
            top = heights[stack.pop()]
            left = stack[-1] + 1 if stack else 0
            best = max(best, top * (i - left))
        stack.append(i)
    return best

The stack keeps indexes with increasing heights. When a shorter bar arrives, each popped bar has found its right limit (the current index) and its left limit (the new top), so its widest rectangle is height * (i - left). Each bar is pushed and popped once: O(n). The trap is forgetting the bars still on the stack at the end; a trailing 0 flushes them.