DSA · Intermediate · Pattern 3 of 10
Monotonic Stack
12 problems.
Your progress0%
- 1st Visit
- 0/12
- 2nd Visit
- 0/12
- Revise
- 0/12
About this pattern
A monotonic stack keeps its elements in increasing or decreasing order; before pushing a new element, it pops every element the newcomer makes irrelevant. At the moment an element is popped, the current element is its next greater (or smaller) element, and the new top of the stack is its previous one.
This answers questions about the nearest larger or smaller value, spans, and how far each element extends as the minimum or maximum of a range. Signals: for each element, find the next or previous greater or smaller element, or maximise an area bounded by heights. Every index is pushed and popped at most once, so the pass is O(n).
// nxt[i] = index of the next strictly greater element, or n if none.
vector<int> nextGreater(const vector<int>& a) {
int n = a.size();
vector<int> nxt(n, n);
stack<int> st; // indices, values decreasing
for (int i = 0; i < n; ++i) {
while (!st.empty() && a[st.top()] < a[i]) {
nxt[st.top()] = i; // a[i] resolves the popped index
st.pop();
}
st.push(i);
}
return nxt;
}