Understanding Monotonic Stack
A Monotonic Stack is a pattern used to solve problems where you must maintain a monotonic (non-increasing or non-decreasing) order of elements. This pattern is particularly useful in problems involving the next greater element, the previous smaller element, and various other applications where maintaining order is necessary.
Process
Initialization: Start by defining the problem space and initializing a stack to keep track of elements in monotonic order.
Iterate Through Elements: Iterate through the elements of the input sequence.
Maintain Monotonic Order:
Non-Increasing Stack: For a non-increasing stack, push elements onto the stack if they are less than or equal to the top element. If the current element is greater than the top element, pop elements from the stack until the stack is empty or the top element is greater than or equal to the current element.
Non-Decreasing Stack: For a non-decreasing stack, push elements onto the stack if they are greater than or equal to the top element. If the current element is less than the top element, pop elements from the stack until the stack is empty or the top element is less than or equal to the current element.
Store Results: While popping elements from the stack, store the results as the problem needs. For example, you might store the index of the next greater element or the previous smaller element.
Termination: The process terminates when all elements have been processed.
When to Use
Next Greater Element: To find the next greater element for each element in an array.
Previous Smaller Element: To find the previous smaller element for each element in an array.
Stock Span Problem: To find the number of consecutive days before a given day where the stock price was less than or equal to the current day's price.
Time Complexity
The monotonic stack algorithm has an O(N) time complexity, where N is the number of elements in the input sequence. Each element is pushed and popped from the stack at most once.
Example problem for better understanding
Thank you for reading!
You can support me by buying me a book.