Monotonic Stack
A stack kept in increasing or decreasing order answers every "next greater / smaller element" question in O(n).
A monotonic stack is a stack whose contents stay sorted (all increasing or all decreasing). Before pushing a new element, you pop everything that would break the order — and each pop is exactly the moment you learn something: the new element is the next greater (or smaller) element for the popped one.
Every index is pushed once and popped at most once → O(n).
- "Next / previous greater or smaller element" for every position.
- "How many days until a warmer temperature?", "stock span", "buildings with a view".
- Largest rectangle in a histogram, maximal rectangle in a binary matrix.
- Sum of subarray minimums, removing k digits to form the smallest number.
| Want | Stack order (bottom → top) | Pop while |
|---|---|---|
| Next greater element | Decreasing | stack top < current |
| Next smaller element | Increasing | stack top > current |
Store indices, not values, so you can compute distances and write results by position.
Template: next greater element
int[] nextGreater(int[] a) {
int n = a.length;
int[] res = new int[n];
Arrays.fill(res, -1);
Deque<Integer> st = new ArrayDeque<>(); // indices, values decreasing
for (int i = 0; i < n; i++) {
while (!st.isEmpty() && a[st.peek()] < a[i]) res[st.pop()] = a[i];
st.push(i);
}
return res; // circular array? loop i over 0..2n-1 with i % n
}
int[] dailyTemperatures(int[] t) {
int[] res = new int[t.length];
Deque<Integer> st = new ArrayDeque<>();
for (int i = 0; i < t.length; i++) {
while (!st.isEmpty() && t[st.peek()] < t[i]) {
int j = st.pop();
res[j] = i - j; // days to wait
}
st.push(i);
}
return res;
}def next_greater(a):
res, st = [-1] * len(a), [] # st holds indices, values decreasing
for i, x in enumerate(a):
while st and a[st[-1]] < x:
res[st.pop()] = x
st.append(i)
return res
def daily_temperatures(t):
res, st = [0] * len(t), []
for i, x in enumerate(t):
while st and t[st[-1]] < x:
j = st.pop()
res[j] = i - j
st.append(i)
return resfunction nextGreater(a: number[]): number[] {
const res = new Array(a.length).fill(-1), st: number[] = [];
for (let i = 0; i < a.length; i++) {
while (st.length && a[st[st.length - 1]] < a[i]) res[st.pop()!] = a[i];
st.push(i);
}
return res;
}
function dailyTemperatures(t: number[]): number[] {
const res = new Array(t.length).fill(0), st: number[] = [];
for (let i = 0; i < t.length; i++) {
while (st.length && t[st[st.length - 1]] < t[i]) {
const j = st.pop()!;
res[j] = i - j;
}
st.push(i);
}
return res;
}Largest rectangle in a histogram
For each bar, the widest rectangle using its height extends until the nearest smaller bar on each side. An increasing stack finds both boundaries: when bar i pops bar j, then i is j's right boundary and the new stack top is j's left boundary.
int largestRectangleArea(int[] h) {
Deque<Integer> st = new ArrayDeque<>();
int best = 0;
for (int i = 0; i <= h.length; i++) {
int cur = i == h.length ? 0 : h[i]; // sentinel 0 flushes the stack
while (!st.isEmpty() && h[st.peek()] > cur) {
int height = h[st.pop()];
int left = st.isEmpty() ? -1 : st.peek();
best = Math.max(best, height * (i - left - 1));
}
st.push(i);
}
return best;
}def largest_rectangle_area(h):
st, best = [], 0
for i, cur in enumerate(h + [0]): # sentinel flushes the stack
while st and h[st[-1]] > cur:
height = h[st.pop()]
left = st[-1] if st else -1
best = max(best, height * (i - left - 1))
st.append(i)
return bestfunction largestRectangleArea(h: number[]): number {
const st: number[] = [];
let best = 0;
for (let i = 0; i <= h.length; i++) {
const cur = i === h.length ? 0 : h[i];
while (st.length && h[st[st.length - 1]] > cur) {
const height = h[st.pop()!];
const left = st.length ? st[st.length - 1] : -1;
best = Math.max(best, height * (i - left - 1));
}
st.push(i);
}
return best;
}Maximal rectangle in a binary matrix = run this per row on column heights of consecutive 1s: O(rows × cols).
- Next Greater Element Ieasy
- Daily Temperaturesmedium
- Next Greater Element IIcircular: iterate 2nmedium
- Online Stock Spanprevious greatermedium
- Remove K Digitsincreasing stack, greedymedium
- Sum of Subarray Minimumsprevious/next smaller → contributionmedium
- 132 Patternmedium
- Largest Rectangle in Histogramhard
- Maximal Rectanglehard
- Trapping Rain Waterstack of bars, fill bounded waterhard
- Keep the stack sorted; pop violators before pushing.
- Each pop answers "next greater/smaller" for the popped index.
- Store indices to compute distances and widths.
- A sentinel at the end flushes remaining elements.
- O(n) total: every index is pushed and popped at most once.