Monotonic Stack
A stack keeps its items in sorted order, which finds the next larger or smaller item in one pass.
A monotonic stack keeps its values in sorted order as you push elements. The order can be increasing or decreasing, depending on the problem.
A decreasing monotonic stack is the most common version. Before pushing a new value x, we pop from the top while the top is smaller than or equal to x. After those pops, pushing x keeps the stack decreasing from bottom to top.
This push rule is the whole idea. A monotonic deque uses the same rule, but a deque also lets you remove old elements from the front, which is useful for sliding window problems.
Example Implementation
This implementation maintains a decreasing monotonic stack.
def mono_stack(insert_entries):
stack = []
for entry in insert_entries:
# Pop smaller (or equal) values so stack stays decreasing.
while stack and stack[-1] <= entry:
stack.pop()
# Do something with the popped item here
stack.append(entry)
For an array nums, if index j pops when you process index i, then i is the first index to the right that satisfies the stack condition for j. In a next-greater-element problem, that means nums[i] is the next greater value for nums[j].