Monotonic Stack
Last updated
Was this helpful?
Last updated
Was this helpful?
A monotonic stack is a stack whose elements are monotonically increasing or descreasing.
Sometimes we store the index of the elements in the stack and make sure the elements corresponding to those indexes in the stack forms a mono-sequence.
If we need to pop smaller elements from the stack before pushing a new element, the stack is decreasing from bottom to top.
Otherwise, it's increasing from bottom to top.
For example,
For a mono-decreasing stack:
we need to pop smaller elements before pushing.
it keep tightening the result as lexigraphically greater as possible. (Because we keep popping smaller elements out and keep greater elements).
If we need to calculate both nextSmaller
and prevSmaller
arrays, we can do it using a mono-stack in one pass.
Take for example, since we are looking for lexigraphically smallest subsequence, we should use mono-increasing stack.
The following code is for