How to Identify and Solve Monotonic Stack Problems ?
Last Updated :
23 Jul, 2025
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.
What is 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 monotonically decreasing or increasing.
Some features of a monotonic stack:
- It is a range of queries in an array of situation
- The minima/maxima elements
- When an element is popped from the monotonic stack, it will never be utilized again.
Key Points to Identify Monotonic Stack Problems:
To identify problems where a monotonic stack may be useful, look for the following characteristics:
- Nearest Greater or Smaller Element: 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.
- Monotonic Property: The term "monotonic" refers to the fact that the stack maintains a specific ordering property. There are two types of monotonic stacks:
- Increasing Monotonic Stack: 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.
- Decreasing Monotonic Stack: 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.
- Problems Involving Element Removal: 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.
- Immediate Neighbours: 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.
- Monotonicity Changes: Some problems involve changing monotonicity requirements during traversal, which can be handled using a combination of increasing and decreasing monotonic stacks.
- Typical Use Cases: 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.
- Problems with Linear Time Constraints: 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.
How to Solve Monotonic Stack Problems ?
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 stack
stack = [];
// iterate through all the elements in the array
for (i = 1 to arr.length)) {
// pop elements from stack if some perticular condition satisfies
while (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 stack
stack.push(i);
}
// At all points in time, the stack maintains its monotonic property
}
Lets discuss some examples for better understanding of these patterns:
Problem Statement: Given an array, print the Next Greater Element (NGE) for every element.
Intuition:
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:
C++
#include <iostream>
#include <stack>
using namespace std;
// prints element and NGE pair for all elements of arr[] of
// size n
void printNGE(int arr[], int n)
{
stack<int> s;
// push the first element to stack
s.push(arr[0]);
// iterate for rest of the elements
for (int i = 1; i < n; i++) {
if (s.empty()) {
s.push(arr[i]);
continue;
}
// if stack is not empty, then pop an element from
// stack. If the popped element is smaller than
// next, then a) print the pair b) keep popping
// while elements are smaller and stack is not empty
while (!s.empty() && s.top() < arr[i]) {
cout << s.top() << " --> " << arr[i] << endl;
s.pop();
}
// push next to stack so that we can find next
// greater for it
s.push(arr[i]);
}
// After iterating over the loop, the remaining elements
// in stack do not have the next greater element, so
// print -1 for them
while (!s.empty()) {
cout << s.top() << " --> " << -1 << endl;
s.pop();
}
}
// Driver code
int main()
{
int arr[] = { 11, 13, 21, 3 };
int n = sizeof(arr) / sizeof(arr[0]);
printNGE(arr, n);
return 0;
}
Java
import java.util.Stack;
public class NextGreaterElement {
// prints element and NGE pair for all elements of arr[] of size n
static void printNGE(int arr[], int n) {
Stack<Integer> s = new Stack<>();
// push the first element to stack
s.push(arr[0]);
// iterate for rest of the elements
for (int i = 1; i < n; i++) {
if (s.empty()) {
s.push(arr[i]);
continue;
}
// if stack is not empty, then pop an element from stack.
// If the popped element is smaller than next, then
// a) print the pair
// b) keep popping while elements are smaller and stack is not empty
while (!s.empty() && s.peek() < arr[i]) {
System.out.println(s.peek() + " --> " + arr[i]);
s.pop();
}
// push next to stack so that we can find next greater for it
s.push(arr[i]);
}
// After iterating over the loop, the remaining elements in stack
// do not have the next greater element, so print -1 for them
while (!s.empty()) {
System.out.println(s.peek() + " --> " + -1);
s.pop();
}
}
// Driver code
public static void main(String[] args) {
int arr[] = { 11, 13, 21, 3 };
int n = arr.length;
printNGE(arr, n);
}
}
Python
def printNGE(arr, n):
stack = []
# push the first element to stack
stack.append(arr[0])
# iterate for rest of the elements
for i in range(1, n):
if not stack:
stack.append(arr[i])
continue
# if stack is not empty, then
# pop an element from stack.
# If the popped element is smaller
# than next, then
# a) print the pair
# b) keep popping while elements are
# smaller and stack is not empty
while stack and stack[-1] < arr[i]:
print(stack.pop(), "-->", arr[i])
# push next to stack so that we can find
# next greater for it
stack.append(arr[i])
# After iterating over the loop, the remaining
# elements in stack do not have the next greater
# element, so print -1 for them
while stack:
print(stack.pop(), "-->", -1)
# Driver code
arr = [11, 13, 21, 3]
n = len(arr)
printNGE(arr, n)
C#
using System;
using System.Collections.Generic;
class Program
{
/* Prints element and NGE pair for all elements of arr[] of size n */
static void PrintNGE(int[] arr, int n)
{
Stack<int> s = new Stack<int>();
/* Push the first element to stack */
s.Push(arr[0]);
// Iterate for rest of the elements
for (int i = 1; i < n; i++)
{
if (s.Count == 0)
{
s.Push(arr[i]);
continue;
}
/* If stack is not empty, then pop an element from stack.
* If the popped element is smaller than the next, then:
* a) print the pair
* b) keep popping while elements are smaller and stack is not empty */
while (s.Count > 0 && s.Peek() < arr[i])
{
Console.WriteLine($"{s.Peek()} --> {arr[i]}");
s.Pop();
}
/* Push next to stack so that we can find the next greater for it */
s.Push(arr[i]);
}
/* After iterating over the loop, the remaining elements in stack
* do not have the next greater element, so print -1 for them */
while (s.Count > 0)
{
Console.WriteLine($"{s.Peek()} --> -1");
s.Pop();
}
}
/* Driver code */
static void Main()
{
int[] arr = { 11, 13, 21, 3 };
int n = arr.Length;
PrintNGE(arr, n);
}
}
// This code is contributed by shivamgupta0987654321
JavaScript
function printNGE(arr, n) {
let stack = [];
// push the first element to stack
stack.push(arr[0]);
// iterate for rest of the elements
for (let i = 1; i < n; i++) {
if (stack.length === 0) {
stack.push(arr[i]);
continue;
}
// if stack is not empty, then
// pop an element from stack.
// If the popped element is smaller
// than next, then
// a) print the pair
// b) keep popping while elements are
// smaller and stack is not empty
while (stack.length !== 0 && stack[stack.length - 1] < arr[i]) {
console.log(stack.pop() + " --> " + arr[i]);
}
// push next to stack so that we can find
// next greater for it
stack.push(arr[i]);
}
// After iterating over the loop, the remaining
// elements in stack do not have the next greater
// element, so print -1 for them
while (stack.length !== 0) {
console.log(stack.pop() + " --> " + -1);
}
}
// Driver code
let arr = [11, 13, 21, 3];
let n = arr.length;
printNGE(arr, n);
Output11 --> 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:
Conclusion:
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.
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