How to Identify and Solve Monotonic Stack Problems ? (original) (raw)

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:

Key Points to Identify Monotonic Stack Problems:

To identify problems where a monotonic stack may be useful, look for the following characteristics:

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 #include using namespace std;

// prints element and NGE pair for all elements of arr[] of // size n void printNGE(int arr[], int n) { stack 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 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.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);

`

Output

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
Previous Smallest Element Solve
Find Next Greater Element in Circular Array Solve
Sum of subarray minimum Solve
Trapping Rain Water problem Solve
Largest Rectangle in Histogram Solve
Maximum people a person can see while standing in a line in both direction Solve

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.