Wednesday, February 21, 2024

Monotonic Stack

Monotonic Stack

1 Introduction to monotonic stack

A monotonic stack is a stack whose elements are monotonically increasing or decreasing.

If we pop greater elements from the stack before pushing a new element, the stack will increase from bottom to top. If we pop lesser elements, the stack will decrease.

The typical paradigm for an increasing monotonic stack is like:

for (int i = 0; i < A.size(); i++) {
    while (!stk.empty() && stk.top() > A[i]) {
        stk.pop();
    }
    stk.push(A[i]);
}

2 What can monotonically increasing stacks do?

Monotonically increasing stacks can be used to solve a variety of algorithmic problems. One common use case is for finding the nearest greater element in an array. By maintaining a stack of elements in increasing order, we can quickly determine the next greater element for each element in the array. Monotonically increasing stacks can also be used for finding the maximum area of a histogram, as well as for solving problems related to dynamic programming and graph algorithms.

2.1 To find the previous less element of each element in a vector with O(n) time.

What is the previous less element of an element in a vector? Suppose there is a vector [3, 8, 9, 6], for each element 3, 8, 9, and 6:

  • There is no previous less element for 3.
  • The previous less element of 8 is 3.
  • The previous less element of 9 is 8.
  • The previous less element of 6 is 3.

Monday, February 19, 2024