Skip to content

Monotonic Stack

Data structure that maintains monotonic properties. It can be monotonically increasing/decreasing/non-increasing/non-decreasing.

Operations

  • push: Inserts into the stack
  • pop: Removes the top element from the stack

Info

The weird thing about the monotonic stack is that it doesn't require every element to be stored in the stack. For instance, if you called 5 push operations, the stack might only contain 3 elements, and pop may not be able to recover all 5 elements pushed.

Implementation

The implementation might be counter-intuitive at first, because there is **no need that all elements in the stack need to be retained. The only requirement is that the elements in the stack must be monotonic.

Push

There are two priorities when inserting an element x:

  1. Maintain the monotonic property
  2. Element x must be in the stack

Question

How do you like my sideways stack?

How to insert element 6 into the stack?

Pop every element that's greater than 6 (> or >= is a design choice), then insert 6 into the stack. The final states should look as follows:

Delete

Similar to a regular stack, just remove the top item of the stack.