02
Next / previous smaller (Monotonic Stack Sub-pattern)
Increasing stack. A smaller arrival pops every bigger waiting element. The same shape powers greedy "make it as small as possible" questions, where the stack is the answer being built.
Signals in the problem statement
- ›
"first price to the right that is lower or equal"
- ›
"next smaller element"
- ›
"remove k digits so the number is smallest"
- ›
"smallest subsequence / remove duplicate letters"
What makes it different
Final Prices pops while top ≥ x (≤ counts). Next Smaller Element shows the other direction: scan right-to-left, throw away candidates that are ≥ the current value, and the top is the answer. Remove K Digits and Remove Duplicate Letters build the answer on the stack: a smaller digit/letter pops bigger ones before it — but only while you're allowed (k > 0, or the popped letter appears again later).
Questions
ordered from “learn the idea” to “recognise it without help”- 1Final Prices With a Special Discount in a ShopWalkthroughEasyBasic Anchor·LeetCode #1475
- 2Next Smaller ElementWalkthroughMediumBasic Reinforcement·GeeksforGeeks
- 3Remove K DigitsWalkthroughMediumPattern Transfer·LeetCode #402
- 4Remove Duplicate LettersWalkthroughMediumInterview-Level·LeetCode #316
Template
next-greater-template.cpp
// Next greater element to the right; -1 if none. Decreasing stack of indices.
vector<int> nextGreater(vector<int>& a) {
int n = a.size();
vector<int> ans(n, -1); // leftovers keep -1
stack<int> st; // indices; values decrease bottom → top
for (int i = 0; i < n; i++) {
while (!st.empty() && a[st.top()] < a[i]) { // a[i] beats the waiting top
ans[st.top()] = a[i]; // answer written on POP
st.pop();
}
st.push(i); // a[i] now waits for its own answer
}
return ans;
}Remember this · Monotonic Stack
Trigger
Next/previous greater or smaller element, spans, histogram areas, "for each element, how far does it dominate?"
Think
When a new element arrives, which older elements can never be the answer again?
Key question
Is my stack increasing or decreasing, and what do I record when I pop?