![]() |
VOOZH | about |
We all know what is Stack and how it works so today we will learn about a special type of data structure called monotonic stack. Problems using monotonic stack are difficult to identify if you do not know its concept. So in this post, we are going to discuss some key points that will help us to identify these problems.
But Before that let's discuss the monotonic stack and its features.
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 monotonically decreasing or increasing.
Some features of a monotonic stack:
To identify problems where a monotonic stack may be useful, look for the following characteristics:
- Monotonic stacks are commonly used to find the nearest greater or smaller element to the left or right of each element in an array or sequence. If a problem requires you to find such elements efficiently, it's a strong indicator that a monotonic stack might be useful.
- The term "monotonic" refers to the fact that the stack maintains a specific ordering property. There are two types of monotonic stacks:
- This stack is used when you need to find the nearest smaller element to the right for each element. It keeps elements in non-decreasing order, meaning the top of the stack contains the largest element seen so far.
- This stack is used when you need to find the nearest greater element to the right for each element. It keeps elements in non-increasing order, meaning the top of the stack contains the smallest element seen so far.
- Monotonic stacks are often used in problems where you need to remove elements from the stack once their purpose is fulfilled. Elements are pushed onto the stack while certain conditions are met, and they are popped when no longer relevant.
- The problems that require finding immediate neighbours, such as the nearest greater or smaller elements to the left or right, are good candidates for a monotonic stack.
- Some problems involve changing monotonicity requirements during traversal, which can be handled using a combination of increasing and decreasing monotonic stacks.
- Monotonic stacks are often used in scenarios like finding the next greater element, next smaller element, calculating the maximum area under histograms, evaluating expressions with infix to postfix conversion, and solving problems related to stock span, building and trapping rainwater, etc.
- If the problem statement mentions that you need to solve it in linear time, or it hints at optimizing the time complexity, a monotonic stack might be beneficial.
There is a particular pattern which we can follow to solve these monotonic stack problems
Pseudo code to solve these problems
function solve(arr) {// initialize an empty stackstack = [];// iterate through all the elements in the arrayfor (i = 1 to arr.length)) {// pop elements from stack if some perticular condition satisfieswhile (stack is not empty && element represented by stack top "OPERATOR" arr[i]) {let stackTop = stack.pop();// do something with stackTop here e.g.// nextGreater[stackTop] = i}if (!stack.empty()) {// if stack has some elements left// do something with stack top here e.g.// previousGreater[i] = stack.at(-1)}// at the end, we push the current index into the stackstack.push(i);}// At all points in time, the stack maintains its monotonic property}
Lets discuss some examples for better understanding of these patterns:
Given an array, print the Next Greater Element (NGE) for every element.
In this problem we need to find out the next greater element of each element so we can use monotonic stack in this question. Why? Because we can store the elements in the stack in increasing order of index and value and if current value of stack does not satisfy the current condition of having greater than current array element then this stack value never contribute in our answer so we can pop this value which maintains the monotonic behaviour of the stack.
Below are the implementation of the above approach:
11 --> 13 13 --> 21 3 --> -1 21 --> -1
Time Complexity : O(N), N is the size of the array.
Auxiliary space : O(N)
All Problems like Next smallest element, Previous greater element, Previous smaller elements can be solved similarly with these technique.
Similar Problems using the same approach:
Problem | Practice Link |
|---|---|
Maximum people a person can see while standing in a line in both direction |
So, when you encounter a problem that involves finding nearest greater or smaller elements, maintaining monotonic properties, and potentially requires linear time complexity, consider using a monotonic stack as a potential approach. It's crucial to understand the problem requirements and constraints before deciding to use this data structure and algorithm.