Open In App

How to Identify and Solve Monotonic Stack Problems ?

Last Updated : 20 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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);
    }
}
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);
Python3
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)

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.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads