Monotonic Stack

A stack kept in increasing or decreasing order answers every "next greater / smaller element" question in O(n).

Intermediate 2 min readLesson 8 of 25

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).

InteractiveMonotonic stack — next greater element
2
0
i
7
1
3
2
5
3
4
4
6
5
8
6
1
7
stack (indices, bottom → top)
empty
result
?
0
?
1
?
2
?
3
?
4
?
5
?
6
?
7
currenton stackresolved
Look at 2
1/23
When to use this pattern
  • "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.
WantStack order (bottom → top)Pop while
Next greater elementDecreasingstack top < current
Next smaller elementIncreasingstack 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;
}

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;
}

Maximal rectangle in a binary matrix = run this per row on column heights of consecutive 1s: O(rows × cols).

Practice problems
  • 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
Key takeaways
  • 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.