A monotonic stack is a special type of stack data structure where elements are kept in either increasing or decreasing order. The main idea is to maintain this order while pushing and popping elements, which helps solve a wide range of problems efficiently.
Understanding Monotonic Stack
A monotonic stack is a stack that maintains its elements in a fixed order either increasing or decreasing.
When a new element is pushed, it is compared with the top of the stack. If the order is violated, elements are popped until the property is restored, and then the new element is pushed.
This way, the stack always stays ordered, and since each element is pushed and popped at most once, the overall operations run in linear time.
Types of Monotonic Stack:
Monotonic Stacks can be broadly classified into two types:
- Monotonic Increasing Stack
- Monotonic Decreasing Stack
Monotonic Increasing Stack
- Elements inside the stack are always in increasing order.
- While inserting a new element, all greater elements are popped.
Example:
For arr[] = [1, 7, 9, 5]:
- Push 1 → [1]
- Push 7 → [1, 7] (since 7 > 1, order holds)
- Push 9 → [1, 7, 9] (since 9 > 7, order holds)
- Push 5 → pop 9, pop 7, then push 5 → [1, 5]
Here we can see that at every step, the stack maintains an increasing order from bottom to top.
For more details refer to below Articles:
Monotonic Decreasing Stack
- Elements inside the stack are always in decreasing order.
- While inserting a new element, all smaller elements are popped.
Example:
For arr[] = [1, 7, 9, 5]:
- Push 1 → [1]
- Push 7 → pop 1, then push 7 → [7]
- Push 9 → pop 7, then push 9 → [9]
- Push 5 → [9, 5] (since 5 < 9, order holds)
Here we can see that at every step, the stack maintains a decreasing order from bottom to top.
For more details refer to below Articles:
Practice Problem on Monotonic Stack
- Stock Span Problem
- Largest Rectangle in Histogram
- Trapping Rain Water
- Find next Smaller of next Greater in an array
- Expression Evaluation
- Lowest Number by Removing k digits