Lesson 2 of 73 2 min

Pattern Blueprint: The Monotonic Stack Template

Learn how to solve "Next Greater Element" and "Largest Area" problems in linear time using a Monotonic Stack blueprint.

The Mental Model

A monotonic stack is a stack that maintains its elements in a strictly increasing or decreasing order. It is the "Silver Bullet" for problems where an element's value depends on its closest greater/smaller neighbors.

1. The "Next Greater Element" Template

public int[] nextGreaterElement(int[] nums) {
    int n = nums.length;
    int[] res = new int[n];
    Stack<Integer> stack = new Stack<>(); // Stores indices

    for (int i = 0; i < n; i++) {
        // While stack is not empty and current element is greater than top
        while (!stack.isEmpty() && nums[i] > nums[stack.peek()]) {
            int prevIndex = stack.pop();
            res[prevIndex] = nums[i]; // Found the next greater!
        }
        stack.push(i);
    }
    
    // Remaining indices in stack have no next greater
    while (!stack.isEmpty()) {
        res[stack.pop()] = -1;
    }
    return res;
}

2. Key Variations

Requirement Property Action
Next Greater Monotonic Decreasing Pop when curr > top
Next Smaller Monotonic Increasing Pop when curr < top
Prev Greater Scan Right to Left Same logic as Next Greater

3. Interview Discussion: The "Aha!" Moment

How do you know it's a Monotonic Stack problem? Look for words like "Nearest," "Closest," or "Next Greater/Smaller." If you find yourself thinking "I need to look back at previous elements to see which ones I just beat," the Monotonic Stack is your best friend.

Want to track your progress?

Sign in to save your progress, track completed lessons, and pick up where you left off.