LeetCode 84: Largest Rectangle in Histogram Explained

Picture a histogram where bars tower like a chaotic skyline. LeetCode 84 asks: what's the largest rectangle you can carve from consecutive bars? A monotonic stack turns this nightmare into genius.

LeetCode 84's Monotonic Stack Trick: Visualizing the Histogram's Hidden Giant Rectangle — theAIcatchup

Key Takeaways

  • Monotonic stack nails O(n) solution by tracking increasing heights and popping for rectangles.
  • Visual tracers like TraceLit make 'Hard' problems intuitive—step through every pop.
  • Master this for interviews; it's a gateway to AI-era pattern mastery.

45% acceptance rate. That’s the brutal stat staring back at you on LeetCode 84—millions of coders humbled by a simple-looking histogram.

And here’s the thrill: it’s not just a puzzle. It’s a portal to the future of coding, where AI agents devour problems like this in seconds, but humans who grok the monotonic stack? We’re the ones steering the ship.

Why Histogram Rectangles Haunt Every Tech Interview?

Think of it — bars of varying heights, each width 1, squeezed together like protesters at a rally. You need the biggest rectangle formed by consecutive ones. Brute force? O(n²) disaster, timeouts galore. But this? O(n) elegance. A stack that only grows with increasing heights, then pops like champagne when a shorter bar crashes the party.

Visualize: stack holds indices of bars, strictly increasing heights. Hit a dwarf? Pop the giants, compute their reign — width from current i minus previous stack top. Boom, area candidate. It’s like a king dethroned, but his legacy (that massive rectangle) lives on.

Use a monotonic stack to track indices of bars in increasing height order. When a shorter bar is encountered, calculate rectangles using previously stored taller bars as heights, with widths determined by the current position and stack contents.

That’s the original wisdom — straight fire. No fluff.

But wait. After the loop? Don’t forget the trailing monarchs. Pop ‘em all, pretend a ghost bar of height 0 ends the array. Width stretches to n. Sneaky, brilliant.

Here’s the code heartbeat:

class Solution:
    def largestRectangleArea(self, heights: List[int]) -> int:
        stack = []
        max_area = 0
        for i in range(len(heights)):
            while stack and heights[i] < heights[stack[-1]]:
                height = heights[stack.pop()]
                width = i if not stack else i - stack[-1] - 1
                max_area = max(max_area, height * width)
            stack.append(i)
        while stack:
            height = heights[stack.pop()]
            width = len(heights) if not stack else len(heights) - stack[-1] - 1
            max_area = max(max_area, height * width)
        return max_area

Step through it. Say heights = [2,1,5,6,2,3]. i=0, stack=[0]. i=1 (1<2), pop 0, width=1-0=1? Wait, i=1, stack empty, width=1, area=2*1=2. Stack=[1]. i=2 (5>1), stack=[1,2]. i=3 (6>5), [1,2,3]. i=4 (2<6), pop3 height6, width=4-2-1=1, area=6. Pop2 height5, width=4-1-1=2, area=10. 2>1? Stack=[1], append4 [1,4]. i=5 (3>2), [1,4,5]. End loop. Pop5 h3 w=6-4-1=1 area=3. Pop4 h2 w=6-1-1=4 area=8. Pop1 h1 w=6 area=6. Max=10.

Magic. That 5-high bar spanning two widths? Caught perfectly.

How Does Monotonic Stack Actually Work Here?

Monotonic — heights non-decreasing on stack. It’s a promise. Violated? Reckon with the past. Like a rising stock market, crash hits, sell peaks before. Width? Right boundary is the killer (current i), left is previous stack top +1. Precise.

Why vivid? Imagine a dam breaking — taller bars flood out, their full span revealed only now. Futurist twist: AI like Devin or Cursor? They’ll ace this. But the insight? Humans invent these stacks. We’re the architects. Bold prediction — in AI’s coding utopia, mastery of monotonicity separates prompt engineers from stack overflowers. (Yeah, pun intended.)

Corporate hype alert. LeetCode calls it ‘Hard.’ Fair. But tools like TraceLit? Game-on. Step every line visually — no more blind faith. It’s open-source beat: explain, empower devs.

Real-world echo. Stock trading volume histograms. Largest rectangle? Biggest trade window without dips killing momentum. Or UI design — pixel-perfect resizable panels. Everywhere.

Historical parallel — think Babylonian math, area under curves approximated by rectangles. Fast-forward, we’re doing it in linear time. Wonder.

Deeper dive. Edge cases? All increasing: stack full, end-pop sweeps max (last bar * n). All same height: each pop width=1, but wait no — actually computes full span correctly on end. Empty? 0. Single bar? Itself.

Proof of O(n): each index pushed/popped once. Amortized perfection.

So, TraceLit shines here — watch the stack morph, areas flash. Try it. Feel the pace.

Will Mastering LeetCode 84 Future-Proof Your Dev Career?

Short answer: hell yes. Interviews at FAANG? This pattern recurs — largest subarray sum, rain water trapping, stock spans. Monotonic stack: Swiss army knife.

AI shift? Agents solve it now. But explain it? Tinker it? That’s human edge. We’re not replaced; augmented. Picture collaborative coding: you sketch intent, AI implements stack. Boom.

Critique: LeetCode’s PR spin — ‘practice for real eng.’ True-ish. But histograms? Rare daily. Skill transfers though. Pattern recognition > memorization.

One para wonder: Practice.

Stretch it. Next challenge: sliding window max? Same stack, deque twist. Universe expands.

Energy check — exhausted yet? Good. Means it’s sticking.


🧬 Related Insights

Frequently Asked Questions

What does LeetCode 84 test exactly? Monotonic increasing stack for O(n) largest contiguous rectangle in histogram heights.

Is the monotonic stack hard to implement? Nah — 15 lines. Key: pop while smaller, width calc with i vs prev.

Why use TraceLit for LeetCode 84? Visual line-by-line trace demystifies stack pops — see areas compute live.

Priya Sundaram
Written by

Hardware and infrastructure reporter. Tracks GPU wars, chip design, and the compute economy.

Frequently asked questions

What does LeetCode 84 test exactly?
Monotonic increasing stack for O(n) largest contiguous rectangle in histogram heights.
Is the monotonic stack hard to implement?
Nah — 15 lines. Key: pop while smaller, width calc with i vs prev.
Why use TraceLit for LeetCode 84?
Visual line-by-line trace demystifies stack pops — see areas compute live.

Worth sharing?

Get the best AI stories of the week in your inbox — no noise, no spam.

Originally reported by Dev.to

Stay in the loop

The week's most important stories from theAIcatchup, delivered once a week.