Monotonic Stack

Photo by Chris Czermak on Unsplash
Photo by Chris Czermak on Unsplash
Monotonic stack is a stack in which the value of the elements inside must be increasing or decreasing.

Monotonic stack is a stack in which the value of the elements inside must be increasing or decreasing.

Table of Contents
  1. Monotonic Stack
  2. Example

Monotonic Stack

The following algorithm generates an increasing monotonic stack. Whenever it is about to push a value x into the stack, it first checks whether the top value of the stack is greater than x, and if so, pop the top value. In this way, it repeatedly checks the value until the top value is less than x, and then pushes x into the stack. Finally, the resulting stack is increasing.

Algorithm IncreasingMonotonicStack(arr) {
    stack := Stack();
    for i in arr {
        while stack.isNotEmpty && stack.peek() > i {
            stack.pop();
        }
        stack.push(i);
    }
    return stack;
}

The following algorithm will generate a decreasing monotonic stack.

Algorithm DecreasingMonotonicStack(arr) {
    stack := Stack();
    for i in arr {
        while stack.isNotEmpty && stack.peek() < i {
            stack.pop();
        }
        stack.push(i);
    }
    return stack;
}

Example

Leave a Reply

Your email address will not be published. Required fields are marked *

You May Also Like
Photo by Pedro Lastra on Unsplash
Read More

Breadth First Search (BFS)

Breadth-first search (BFS) algorithm is a graph search algorithm. Starting from a given vertex, it first explores all adjacent vertices of that vertex. Next, explores the adjacent vertices of these adjacent vertices in sequence. In this way, it explores level by level until the result is found, or all vertices are explored.
Read More
Photo by Léonard Cotte on Unsplash
Read More

Depth First Search (DFS)

Depth-first search (DFS) algorithm is a graph search algorithm. Starting from a given vertex, it first explores an adjacent vertex of that vertex. Next, it explores an adjacent vertex of this vertex. In this way, the exploration continues until a certain vertex has no adjacent vertices, it will return to the previous vertex, and explores the next adjacent vertex of the vertex. It will continue to explore like this until it finds a result, or explores all vertices.
Read More
Photo by Anthony DELANOIX on Unsplash
Read More

Union Find

Union Find data structure is also known as disjoint set data structure. It is a data structure which stores a collection of disjoint sets. It provides two operations, one for merging two sets and one for finding the set with a given element.
Read More