Browse curriculum

FAANGPrep Sprint

Largest Rectangle in Histogram

Find the area of the largest rectangle in the histogram.

Problem Understanding

heights lists the bars of a histogram from left to right, each bar one unit wide. Return the area of the biggest rectangle that fits entirely inside the bars.

Example:

  • Input: [2, 1, 5, 6, 2, 3]
  • Output: 10 (The rectangle from index 2 to 3 with height 5 has area 5 * 2 = 10).

Algorithm Strategy

We use a Monotonic Increasing Stack.

Core Idea:
For each bar h at index i, if we know the first bar to the left that is smaller (left_limit) and the first bar to the right that is smaller (right_limit), then the maximum width for a rectangle with height h is right_limit - left_limit - 1.

One-Pass Logic:

  1. Maintain a stack of indices with increasing heights.
  2. When we encounter a bar h[i] smaller than h[stack.top()], it means h[i] is the Right Limit for h[stack.top()].
  3. Pop top. Now the New Top of the stack is the Left Limit for the popped bar.
  4. Calc Area: height * (i - stack.top() - 1).
  5. Repeat until stack rule is satisfied, then push i.

Interactive Visualization

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

BASE -1

heights

2

0

1

1

5

2

6

3

2

4

3

5

stack · indices

-1

TOP · base

h

—

Area

—

Best

0

 

Start the stack with -1: the left edge for a bar with nothing shorter before it

Next

i = 0: h = 2

Heights

Visualize how we pop bars when a shorter one appears, calculating potential areas.