Introduction to Monotonic Stack - Data Structure and Algorithm Tutorials
Last Updated :
23 Jul, 2025
A monotonic stack is a special data structure used in algorithmic problem-solving. Monotonic Stack maintaining elements in either increasing or decreasing order. It is commonly used to efficiently solve problems such as finding the next greater or smaller element in an array etc.
Monotonic StackWhat is Monotonic Stack?
A Monotonic Stack is a common data structure in computer science that maintains its elements in a specific order. Unlike traditional stacks, Monotonic Stacks ensure that elements inside the stack are arranged in an increasing or decreasing order based on their arrival time. In order to achieve the monotonic stacks, we have to enforce the push and pop operation depending on whether we want a monotonic increasing stack or monotonic decreasing stack.
Let's understand the term Monotonic Stacks by breaking it down.
Monotonic: It is a word for mathematics functions. A function y = f(x) is monotonically increasing or decreasing when it follows the below conditions:
- As x increases, y also increases always, then it's a monotonically increasing function.
- As x increases, y decreases always, then it's a monotonically decreasing function.
See the below examples:
- y = 2x +5, it's a monotonically increasing function.
- y = -(2x), it's a monotonically decreasing function.
Similarly, A stack is called a monotonic stack if all the elements starting from the bottom of the stack is either in increasing or in decreasing order.
Types of Monotonic Stack:
Monotonic Stacks can be broadly classified into two types:
- Monotonic Increasing Stack
- Monotonic Decreasing Stack
Monotonic Increasing Stack:
A Monotonically Increasing Stack is a stack where elements are placed in increasing order from the bottom to the top. Each new element added to the stack is greater than or equal to the one below it. If a new element is smaller, we remove elements from the top of the stack until we find one that is smaller or equal to the new element, or until the stack is empty. This ensures that the stack always stays in increasing order.
Example: 1, 3, 10, 15, 17
How to achieve Monotonic Increasing Stack?
To achieve a monotonic increasing stack, you would typically push elements onto the stack while ensuring that the stack maintains a increasing order from bottom to top. When pushing a new element, you would pop elements from the stack that are greater than the new element until the stack maintains the desired monotonic increasing property.
To achieve a monotonic increasing stack, you can follow these step-by-step approaches:
- Initialize an empty stack.
- Iterate through the elements and for each element:
- while stack is not empty AND top of stack is more than the current element
- pop element from the stack
- Push the current element onto the stack.
- At the end of the iteration, the stack will contain the monotonic increasing order of elements.
Let's illustrate the example for a monotonic increasing stack using the array Arr[] = {1, 7, 9, 5}:
Below is the implementation of the above approach:
C++
#include <iostream>
#include <stack>
#include <vector>
using namespace std;
// Function to implement monotonic increasing stack
vector<int> monotonicIncreasing(vector<int>& nums)
{
int n = nums.size();
stack<int> st;
vector<int> result;
// Traverse the array
for (int i = 0; i < n; ++i) {
// While stack is not empty AND top of stack is more
// than the current element
while (!st.empty() && st.top() > nums[i]) {
// Pop the top element from the
// stack
st.pop();
}
// Push the current element into the stack
st.push(nums[i]);
}
// Construct the result array from the stack
while (!st.empty()) {
result.insert(result.begin(), st.top());
st.pop();
}
return result;
}
int main() {
// Example usage:
vector<int> nums = {3, 1, 4, 1, 5, 9, 2, 6};
vector<int> result = monotonicIncreasing(nums);
cout << "Monotonic increasing stack: ";
for (int num : result) {
cout << num << " ";
}
cout << endl;
return 0;
}
Java
import java.util.ArrayDeque;
import java.util.Deque;
public class MonotonicIncreasingStack {
// Function to implement monotonic increasing stack
public static int[] monotonicIncreasing(int[] nums) {
Deque<Integer> stack = new ArrayDeque<>();
// Traverse the array
for (int num : nums) {
// While stack is not empty AND top of stack is more than the current element
while (!stack.isEmpty() && stack.peekLast() > num) {
// Pop the top element from the stack
stack.pollLast();
}
// Push the current element into the stack
stack.offerLast(num);
}
// Construct the result array from the stack
int[] result = new int[stack.size()];
int index = stack.size() - 1;
while (!stack.isEmpty()) {
result[index--] = stack.pollLast();
}
return result;
}
// Main method for example usage
public static void main(String[] args) {
// Example usage:
int[] nums = {3, 1, 4, 1, 5, 9, 2, 6};
int[] result = monotonicIncreasing(nums);
System.out.print("Monotonic increasing stack: [");
for (int i = 0; i < result.length; i++) {
System.out.print(result[i]);
if (i != result.length - 1) {
System.out.print(", ");
}
}
System.out.println("]");
}
}
Python
def monotonicIncreasing(nums):
stack = []
result = []
# Traverse the array
for num in nums:
# While stack is not empty AND top of stack is more than the current element
while stack and stack[-1] > num:
# Pop the top element from the stack
stack.pop()
# Push the current element into the stack
stack.append(num)
# Construct the result array from the stack
while stack:
result.insert(0, stack.pop())
return result
# Example usage:
nums = [3, 1, 4, 1, 5, 9, 2, 6]
result = monotonicIncreasing(nums)
print("Monotonic increasing stack:", result)
JavaScript
// Function to implement monotonic increasing stack
function monotonicIncreasing(nums) {
const stack = [];
const result = [];
// Traverse the array
for (let i = 0; i < nums.length; ++i) {
// While stack is not empty AND top of stack is more than the current element
while (stack.length > 0 && stack[stack.length - 1] > nums[i]) {
// Pop the top element from the stack
stack.pop();
}
// Push the current element into the stack
stack.push(nums[i]);
}
// Construct the result array from the stack
while (stack.length > 0) {
result.unshift(stack.pop());
}
return result;
}
// Example usage:
const nums = [3, 1, 4, 1, 5, 9, 2, 6];
const result = monotonicIncreasing(nums);
console.log("Monotonic increasing stack:", result);
OutputMonotonic increasing stack: 1 1 2 6
Complexity Analysis:
- Time Complexity: O(N), each element from the input array is pushed and popped from the stack exactly once. Therefore, even though there is a loop inside a loop, no element is processed more than twice.
- Auxiliary Space: O(N)
Monotonic Decreasing Stack:
A Monotonically Decreasing Stack is a stack where elements are placed in decreasing order from the bottom to the top. Each new element added to the stack must be smaller than or equal to the one below it. If a new element is greater than top of stack then we remove elements from the top of the stack until we find one that is greater or equal to the new element, or until the stack is empty. This ensures that the stack always stays in decreasing order.
Example: 17, 14, 10, 5, 1
How to achieve Monotonic Decreasing Stack?
To achieve a monotonic decreasing stack, you would typically push elements onto the stack while ensuring that the stack maintains a decreasing order from bottom to top. When pushing a new element, you would pop elements from the stack that are greater than the new element until the stack maintains the desired monotonic decreasing property.
To achieve a monotonic decreasing stack, you can follow these step-by-step approaches:
- Start with an empty stack.
- Iterate through the elements of the input array.
- While stack is not empty AND top of stack is less than the current element:
- pop element from the stack
- Push the current element onto the stack.
- After iterating through all the elements, the stack will contain the elements in monotonic decreasing order.
Let's illustrate the example for a monotonic decreasing stack using the array Arr[] = {7, 5, 9, 4}:
B4elow is the implementation of the above approach:
C++
#include <iostream>
#include <stack>
#include <vector>
using namespace std;
// Function to implement monotonic decreasing stack
vector<int> monotonicDecreasing(vector<int>& nums) {
int n = nums.size();
stack<int> st;
vector<int> result(n);
// Traverse the array
for (int i = 0; i < n; ++i) {
// While stack is not empty AND top of stack is less than the current element
while (!st.empty() && st.top() < nums[i]) {
st.pop();
}
// Construct the result array
if (!st.empty()) {
result[i] = st.top();
} else {
result[i] = -1;
}
// Push the current element into the stack
st.push(nums[i]);
}
return result;
}
int main() {
vector<int> nums = {3, 1, 4, 1, 5, 9, 2, 6};
vector<int> result = monotonicDecreasing(nums);
cout << "Monotonic decreasing stack: ";
for (int val : result) {
cout << val << " ";
}
cout << endl;
return 0;
}
Java
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
public class MonotonicDecreasing {
public static List<Integer> monotonicDecreasing(int[] nums) {
Stack<Integer> stack = new Stack<>();
List<Integer> result = new ArrayList<>();
// Traverse the array
for (int num : nums) {
// While stack is not empty AND top of stack is less than the current element
while (!stack.isEmpty() && stack.peek() < num) {
// Pop the top element from the stack
stack.pop();
}
// Construct the result array
if (!stack.isEmpty()) {
result.add(stack.peek());
} else {
result.add(-1);
}
// Push the current element into the stack
stack.push(num);
}
return result;
}
public static void main(String[] args) {
int[] nums = {3, 1, 4, 1, 5, 9, 2, 6};
List<Integer> result = monotonicDecreasing(nums);
System.out.println("Monotonic decreasing stack: " + result);
}
}
Python
def monotonicDecreasing(nums):
stack = []
result = []
# Traverse the array
for num in nums:
# While stack is not empty AND top of stack is less than the current element
while stack and stack[-1] < num:
# Pop the top element from the stack
stack.pop()
# Construct the result array
if stack:
result.append(stack[-1])
else:
result.append(-1)
# Push the current element into the stack
stack.append(num)
return result
# Example usage:
nums = [3, 1, 4, 1, 5, 9, 2, 6]
result = monotonicDecreasing(nums)
print("Monotonic decreasing stack:", result)
JavaScript
function monotonicDecreasing(nums) {
let stack = [];
let result = [];
// Traverse the array
for (let num of nums) {
// While stack is not empty AND top of stack is less than the current element
while (stack.length && stack[stack.length - 1] < num) {
// Pop the top element from the stack
stack.pop();
}
// Construct the result array
if (stack.length) {
result.push(stack[stack.length - 1]);
} else {
result.push(-1);
}
// Push the current element into the stack
stack.push(num);
}
return result;
}
// Example usage:
let nums = [3, 1, 4, 1, 5, 9, 2, 6];
let result = monotonicDecreasing(nums);
console.log("Monotonic decreasing stack:", result);
OutputMonotonic decreasing stack: -1 3 -1 4 -1 -1 9 9
Complexity Analysis:
- Time Complexity: O(N), each element is processed only twice, once for the push operation and once for the pop operation.
- Auxiliary Space: O(N)
Practice Problem on Monotonic Stack:
Applications of Monotonic Stack :
Here are some applications of monotonic stacks:
- Finding Next Greater Element: Monotonic stacks are often used to find the next greater element for each element in an array. This is a common problem in competitive programming and has applications in various algorithms.
- Finding Previous Greater Element: Similarly, monotonic stacks can be used to find the previous greater element for each element in an array.
- Finding Maximum Area Histogram: Monotonic stacks can be applied to find the maximum area of a histogram. This problem involves finding the largest rectangular area possible in a given histogram.
- Finding Maximum Area in Binary Matrix: Monotonic stacks can also be used to find the maximum area of a rectangle in a binary matrix. This is a variation of the maximum area histogram problem.
- Finding Sliding Window Maximum/Minimum: Monotonic stacks can be used to efficiently find the maximum or minimum elements within a sliding window of a given array.
- Expression Evaluation: Monotonic stacks can be used to evaluate expressions involving parentheses, such as checking for balanced parentheses or evaluating the value of an arithmetic expression.
Advantages of Monotonic Stack:
- Efficient for finding the next greater or smaller element in an array.
- Useful for solving a variety of problems, such as finding the nearest smaller element or calculating the maximum area of histograms.
- In many cases, the time complexity of algorithms using monotonic stacks is linear, making them efficient for processing large datasets.
Disadvantages of Monotonic Stack:
- Requires extra space to store the stack.
- May not be intuitive for beginners to understand and implement.
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem