Monotonic Stack Explained: Next Greater Element & Histogram Problems
October 16, 2026 · 6 min read
Whenever a problem asks for the **next greater**, **next smaller**, or **previous smaller** element for every item in an array, brute force scans right for each index in `O(n²)`. A monotonic stack solves it in `O(n)` because each element is pushed and popped at most once.
Keep the stack sorted by popping dominated items
function dailyTemperatures(temps) {
const res = Array(temps.length).fill(0);
const stack = []; // stores indices with decreasing temperatures
for (let i = 0; i < temps.length; i++) {
while (stack.length && temps[i] > temps[stack[stack.length - 1]]) {
const prev = stack.pop();
res[prev] = i - prev;
}
stack.push(i);
}
return res;
}Tip: store **indices** on the stack rather than values — you can always look up `temps[idx]`, and having the index lets you compute distances and widths directly.