Monotonic Stack
public class Solution {
public static void main(String[] args) {
int[] nums = new int[]{1,2,3,4,5};
Stack<Integer> stack = new Stack<>();
// Iterating using indexes as we might store indexes rather than values
for(int i=0;i<nums.length;i++) {
// Here operator can be filled according to the given condition
// Strictly increasing (>)
// Non-decreasing (>=)
// Strictly decreasing (<)
// Non-increasing (<=)
while(!stack.isEmpty() && stack.peek() `OPERATOR` nums[i]) {
int stackTop = stack.pop();
// do something with stackTop here e.g.
// nextGreater[stackTop] = i
}
if(!stack.isEmpty()) {
// if stack has some elements left
// do something with stack top here e.g.
// previousGreater[i] = stack.peek()
}
stack.push(i);
}
}
}

Monotonic Stack Types
Problem
Stack Type
Operator in while loop
Assignment Position
Time Complexity
Operation
Best
Worst
Average
Explanation
Space Complexity
Operation
Best
Worst
Average
Explanation
Problems
References:
Last updated