Note Time O(n), Space O(n). Each element is pushed and popped at most once. Used in: stock span, daily temperatures, histogram problems. For circular arrays, iterate through the array twice (use i % n).
A stack that maintains elements in sorted order (increasing or decreasing).
Before pushing, pop all elements that violate the ordering.
Used for: next greater/smaller, largest rectangle in histogram.
example
// JavaScript — Largest rectangle in histogramfunction largestRectangle(heights) {
const stack = []; // indices of increasing heightslet maxArea = 0;
for (let i = 0; i <= heights.length; i++) {
const h = i < heights.length ? heights[i] : 0;
while (stack.length > 0 && h < heights[stack[stack.length - 1]]) {
const height = heights[stack.pop()];
const width = stack.length === 0 ? i : i - stack[stack.length - 1] - 1;
maxArea = Math.max(maxArea, height * width);
}
stack.push(i);
}
return maxArea;
}
# Pythondef largest_rectangle(heights):
stack = []
max_area = 0for i in range(len(heights) + 1):
h = heights[i] if i < len(heights) else0while stack and h < heights[stack[-1]]:
height = heights[stack.pop()]
width = i ifnot stack else i - stack[-1] - 1
max_area = max(max_area, height * width)
stack.append(i)
return max_area
Note Time O(n), Space O(n). The sentinel value (appending 0 at the end) forces all remaining bars to be processed. This is a hard problem but the monotonic stack template is reusable. Variant: maximal rectangle in a binary matrix applies this per row.