What exactly is a monotonic stack? (and e.g. how is it different from a monotonic queue?)
E.g. consider the following array of integers: [0, 2, 1, 3, 4]
. If I process this array left to right inserting it into a monotonically decreasing stack, what am I supposed to see in the stack, and why?
Here's an example for a monotonically decreasing stack in Python that apparently is used in many solutions that solve the odd-even jump problem:
def make(A):
result = [None] * N
stack = [] # invariant: stack is decreasing
for i in A:
while stack and i > stack[-1]:
result[stack.pop()] = i
stack.append(i)
return result
If I run it on the following input A = [0, 2, 1, 3, 4]
I get [2, 3, 3, 4, None]
. I find it odd because it includes two 3's, and a None
value. Is this actually correctly implementing a monotonic stack?
A monotonic stack is a stack whose elements are monotonically increasing or decreasing. It contains all qualities that a typical stack has and its elements are all monotonic decreasing or increasing.
Monotonic stack is a stack that from top to bottom, elements are monotonically increasing. From right to left, we can check whether the top of the stack is bigger than the one in array. If it is not bigger than the one in array, it cannot be the solution, since the one in array is farther than it.
Definition of Monotonic Queue A monotonic Queue is a data structure the elements from the front to the end is strictly either increasing or decreasing. For example, there is an line at the hair salon, and you would naturally start from the end of the line.
The word "monotonic" means a list or a function is either always increasing, or always decreasing. In that case, a "monotonic stack" or a "monotonic deque" is a stack or a deque that has this property.
In your example result
is not a monotonic stack. I think you got confused because the description of the solution to the problem alludes to the use of a "monotonic stack", and the function name make
may give you the impression that it's building it. But that's not the case.
A monotonic decreasing stack is a stack that will produce, when popping its elements a sequence that:
In this case, the function make
uses the construction of a monotonic stack (the variable stack
) to identify the "next greater index" (stored in result
) for each (index) value in the array A. This is because the process of building the monotonic stack happens to identify the "next greater index" of the input as you are purging items that should not be included in the output (as per the properties above) as you stack new items.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With