A monotonic stack is a stack that maintains the elements in a way that preserves their monotonic order. Monotonic stacks are often used in problems that require finding the next greater or smaller element for each element in an array in O(n) time.
Implementation
A generic template
Find next greater element
Find previous greater element
Find next smaller element
Find previous smaller element
Summary
Problem
Stack Type
Operator in while loop
Assignment Position
next greater
decreasing (equal allowed)
stackTop < current
inside while loop
previous greater
decreasing (strict)
stackTop ⇐ current
outside while loop
next smaller
increasing (equal allowed)
stackTop > current
inside while loop
previous smaller
increasing (strict)
stackTop >= current
outside while loop
next greater decreasing (equal allowed) stackTop < current inside while loop
previous greater decreasing (strict) stackTop <= current outside while loop
next smaller increasing (equal allowed) stackTop > current inside while loop
previous smaller increasing (strict) stackTop >= current outside while loop