Topics/Stack & Monotonic Stack/Histogram rectangle

Pattern

Histogram rectangle

Histogram rectangle is a reusable approach under Stack & Monotonic Stack. Once you recognize the shape of the input and the ask, this pattern gives you a standard plan instead of inventing a new algorithm from scratch.

Stack & Monotonic StackLinear DSPattern

When to use it

Reach for Histogram rectangle when a stack & monotonic stack problem matches the cues in this lesson — especially after you’ve ruled out a brute-force nested scan.

How it works

  1. Restate the Stack & Monotonic Stack problem in one sentence and name the constraint that Histogram rectangle exploits.
  2. Sketch the invariant Histogram rectangle maintains (what stays true after each step).
  3. Walk a tiny example by hand, writing the state after every update.
  4. Translate that walk into code in your interview language, then list edge cases.

Solution

Reference implementation in C#, Python, Java, JavaScript, and C++.

Exact solutionHistogram rectangle

Why interviewers care

Interviewers grade pattern recognition. Naming Histogram rectangle early shows you can classify the problem inside Linear DS.

Drill Histogram rectangle with Stack & Monotonic Stack problems — filter the bank and solve 2–3 Easy/Medium items while saying the invariant out loud.

Watch-outs

  • !Forgetting remaining stack items
  • !Storing values instead of indices when width matters
Loading visualization…

Practice this

Related Stack & Monotonic Stack problems — open any one and apply Histogram rectangle.

Search bank →

More under Stack & Monotonic Stack

← Back to Stack & Monotonic Stack lesson