Browse Curriculum
Stack
Medium

Overview (Monotonic Stack)

Understand the Monotonic Stack pattern for finding Next Greater/Smaller Elements.
10 min

What is a Monotonic Stack?

A Monotonic Stack is a stack where elements are always sorted (either increasing or decreasing). It allows us to solve problems related to Next Greater Element or Next Smaller Element in O(N) time.

  • Monotonic Increasing: [1, 2, 5, 8]. Used to find the Next Smaller Element.
  • Monotonic Decreasing: [10, 8, 4, 1]. Used to find the Next Greater Element.

How It Works

We iterate through an array. Before pushing a new element X, we Pop all elements from the stack that violate the monotonic property.

Example (Next Greater Element):
We want a Decreasing Stack. If current X > Stack.Top, it means X is the "Next Greater Element" for Stack.Bottom. We pop until X < Stack.Top, then push X.

Interactive Visualization

Step 1 / 1
Empty Stack
Top Index: -1

Initializing...

1x

Visualize the Monotonic Stack process using the Daily Temperatures problem.

Stop Guessing, Start Mastering.

Build the FAANG intuition. Master this pattern with optimized implementations, visual dry runs, and our curated collection of high-yield problems.