2Brute2Best
🔥0
01

Next / previous greater (Monotonic Stack Sub-pattern)

Decreasing stack. A bigger arrival pops every smaller waiting element and becomes their next greater. Whatever never gets popped has no answer.

Signals in the problem statement
  • ›

    "next greater element", "first bigger to the right"

  • ›

    "how many days until a warmer temperature"

  • ›

    circular array ("search wraps around")

  • ›

    cars catching up with each other and forming fleets

What makes it different

Next Greater Element I stores the answers in a map because they're asked for another array. Daily Temperatures pushes indices because the answer is a distance. Next Greater Element II loops twice over the circle (i % n). Car Fleet is the disguised one: sort cars by position from the target backwards and compute arrival times; a car that would arrive no later than the fleet ahead just joins it. The stack keeps fleet times that strictly increase.

Questions

ordered from “learn the idea” to “recognise it without help”
  1. 1
    Next Greater Element I
    Basic Anchor·LeetCode #496
    Easy
  2. 2
    Daily Temperatures
    Basic Reinforcement·LeetCode #739
    Medium
  3. 3
    Next Greater Element II (circular)
    Slight Variation·LeetCode #503
    Medium
  4. 4
    Car Fleet
    Pattern Transfer·LeetCode #853
    Medium

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?