Skip to content
We areTOP 1%
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;
}

Problems

Monotonic Stack questions
#ProblemPlatformDifficultyOpen1st1st Visit2nd2nd VisitRevRevise
1Next Greater Element ILeetCodeEasy Solve Next Greater Element I on LeetCode (opens in a new tab)
2Bad PricesCodeforcesEasy 1100Solve Bad Prices on Codeforces (opens in a new tab)
3Minimum NotationCodeforcesEasy 1200Solve Minimum Notation on Codeforces (opens in a new tab)
4Next Greater Element IILeetCodeMedium Solve Next Greater Element II on LeetCode (opens in a new tab)
5Daily TemperaturesLeetCodeMedium Solve Daily Temperatures on LeetCode (opens in a new tab)
6Online Stock SpanLeetCodeMedium Solve Online Stock Span on LeetCode (opens in a new tab)
7Remove K DigitsLeetCodeMedium Solve Remove K Digits on LeetCode (opens in a new tab)
8Largest SubsequenceCodeforcesMedium 1400Solve Largest Subsequence on Codeforces (opens in a new tab)
9Sum of Subarray MinimumsLeetCodeMedium Solve Sum of Subarray Minimums on LeetCode (opens in a new tab)
10Skyscrapers (easy version)CodeforcesMedium 1500Solve Skyscrapers (easy version) on Codeforces (opens in a new tab)
11Largest Rectangle in HistogramLeetCodeHard Solve Largest Rectangle in Histogram on LeetCode (opens in a new tab)
12Maximal RectangleLeetCodeHard Solve Maximal Rectangle on LeetCode (opens in a new tab)

Sign in to track your progress

Your checkboxes, streak and activity heatmap are saved to your account and sync across devices. It is free.
Sign in with email

New here? Create an account