stacked_bar_chartMonotonic Stack

Monotonic Stack: when to spot it, explain it, and practice it

Monotonic stack is how you turn repeated nearest-boundary searches into one pass. When every element wants to know who defeats it first on the left or right, the stack is doing structural compression for you.

Pattern coverage

25+

Best first move

Choose increasing or decreasing stack based on what should remain unresolved.

Common failure point

Using values instead of indices and losing distance information.

When this pattern should come to mind

The problem asks for the next greater, next smaller, or nearest boundary element.
Every element seems to scan outward until a condition breaks.
You need span widths, histogram ranges, or temperature-style waiting distances.

Checklist before you code

Choose increasing or decreasing stack based on what should remain unresolved.
Store indices if future width or distance matters.
Define what it means when an element is popped.
Handle remaining stack items after the main pass if needed.

The solving flow that works well in interviews

1

Decide what unresolved property the stack maintains.

2

Push indices while the monotonic invariant holds.

3

Pop while the current value resolves earlier items.

4

Record answers at pop time because that is when the boundary becomes known.

5

Process leftovers for default answers or widths.

Common variants

Next greater / smaller

The most direct monotonic-stack pattern.

Boundary width

Find the left and right boundary for each bar or element.

Circular scan

Iterate twice when the array wraps around logically.

Template preview

PythonPublic preview
stack = []
for i, value in enumerate(nums):
    while stack and nums[stack[-1]] < value:
        prev_index = stack.pop()
        # value is the next greater for prev_index
    stack.append(i)

A more useful problem ladder for practice

This is not a random list. It is ordered to help candidates build recognition first, add key variants next, and then increase pressure with harder cases.

High-frequency mistakes

warning

Using values instead of indices and losing distance information.

warning

Choosing the wrong comparison operator for equal elements.

warning

Forgetting the second pass in circular-array questions.

warning

Missing sentinel handling in histogram problems.

Recommended practice path

1

Start with daily temperatures and next greater element.

2

Then solve histogram rectangle problems.

3

Add circular variants next.

4

Finish with harder contribution-counting problems that use boundaries indirectly.

Monotonic Stack Pattern Guide | LeetCode Interview Prep - Interview AiBox