Skip to main content

Monotonic Stack

It's an algorithm that ensures that data in the stack is always following one direction - increasing or decreasing.

Mental model to remember the direction

When we say an increasing monotonic stack, it means the push operation ensures that the new value is increasing. Meaning, the new value must be more than the current top of the stack.

When we say a decreasing monotonic stack, it means the push operation ensures that the new value is decreasing. Meaning, the new value must be lesser than the current top of the stack.

Maintaining monotonicity

If the new value breaks the monotonicity, it will pop all the values that breaks this and then pushes the new value.

Using in coding problems

Keep in mind always that the value in the stack need not be just an integer. We can even keep complex structures. It's the push function that knows what's the value structure is and it can dig through the value to get the actual property which is controlling the monotonicity property of the stack.